Valgrind - strcpy的大小为1的写入无效

时间:2014-11-01 03:23:59

标签: c

我的swapData函数基本上在char *

类型的两个节点之间交换数据
17 void swapData(struct Node *node1, struct Node *node2)
18 {
19     // Create a new node "temp" that stores the data of node2
20     struct Node *temp = (struct Node *)malloc(sizeof(struct Node));
21     temp->data = malloc(strlen(node2->data));
22    
23     strcpy(temp->data,node2->data);
24    
25     // Copy data from node1 to node2
26     strcpy(node2->data,node1->data);
27    
28     // Copy data from temp to node1
29     strcpy(node1->data,temp->data);
30    
31     free(temp->data);
32     free(temp);
33  }

每当我运行valgrind时,它一直给我这个输出:

==27570== Invalid write of size 1
==27570==    at 0x4C2C00F: strcpy (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==27570==    by 0x400794: swapData (test4.c:23)
==27570==    by 0x400A9C: sort (list2.c:20)
==27570==    by 0x40086B: main (test4.c:49)
==27570==  Address 0x51f11dd is 0 bytes after a block of size 13 alloc'd
==27570==    at 0x4C2B6CD: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==27570==    by 0x40076B: swapData (test4.c:21)
==27570==    by 0x400A9C: sort (list2.c:20)
==27570==    by 0x40086B: main (test4.c:49)
==27570==
==27570== Source and destination overlap in strcpy(0x51f1130, 0x51f1130)
==27570==    at 0x4C2C085: strcpy (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==27570==    by 0x4007B2: swapData (test4.c:26)
==27570==    by 0x400A9C: sort (list2.c:20)
==27570==    by 0x40086B: main (test4.c:49)
==27570==
==27570== Invalid read of size 1
==27570==    at 0x4C2C002: strcpy (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==27570==    by 0x4007D0: swapData (test4.c:29)
==27570==    by 0x400A9C: sort (list2.c:20)
==27570==    by 0x40086B: main (test4.c:49)
==27570==  Address 0x51f11dd is 0 bytes after a block of size 13 alloc'd
==27570==    at 0x4C2B6CD: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==27570==    by 0x40076B: swapData (test4.c:21)
==27570==    by 0x400A9C: sort (list2.c:20)
==27570==    by 0x40086B: main (test4.c:49)
==27570==

我认为问题在于swapData中的strcpy。有人能告诉我发生了什么吗?

2 个答案:

答案 0 :(得分:12)

你需要为temp-> data

再多一个字节
temp->data = malloc(strlen(node2->data)+1);

这是因为您需要存储最后一个字节,然后'\ 0'表示字符串的结尾。

答案 1 :(得分:8)

您不仅需要在malloc长度中添加一个,而且还不能像使用strcpy那样交换字符串。如果第一个字符串用10个字节进行malloced而第二个字符串有29个字节怎么办?复制到swap时,您将超出第一个字符串的缓冲区。交换指针最好。如果将data定义为固定长度数组,那么您正在做的是正常的,但temp也可以是相同大小的数组而不是节点。