[英]Correct use of malloc and strcat to avoid memory errors with valgrind
I have stored vertices in my tempStorage : 我已经在tempStorage中存储了顶点:
typedef struct {
int pred[8];
int succ[8];
} arc_set;
arc_set tempStorage;
for example .pred are 0,1,1,2,2 and .succ are 2,2,3,3,1 例如.pred是0,1,1,2,2和.succ是2,2,3,3,1
I have made a char *links = malloc(sizeof(char) * 100);
我做了一个
char *links = malloc(sizeof(char) * 100);
to store these numbers and print them like this: 存储这些数字并像这样打印它们:
char *temp = malloc(10);
for (int l = 0; l < 8; l++){
sprintf(temp, "%d-%d ", tempStorage.pred[l], tempStorage.succ[l]);
strcat(links, temp);
}
free(temp);
fprintf(stdout, "Solution %d edges: %s",countLinks, links);
fprintf(stdout, "\n");
storing strings in format "%d-%d " in temp with sprintf
and then with strcat
concat that with links. 使用
sprintf
然后使用带有链接的strcat
concat将temp格式的字符串存储为“%d-%d”格式。
it does print everything correctly but when I test it with valgrind --leak-check=full --track-origins=yes -v ./programname
I do get: 它确实可以正确打印所有内容,但是当我用
valgrind --leak-check=full --track-origins=yes -v ./programname
我得到了:
Conditional jump or move depends on uninitialised value(s)
==12322== at 0x4C2C66A: strcat (vg_replace_strmem.c:307)
==12322== by 0x4013CC: main (program.c:251)
==12322== Uninitialised value was created by a heap allocation
==12322== at 0x4C29BC3: malloc (vg_replace_malloc.c:299)
==12322== by 0x401270: main (program.c:225)
where c:251 is strcat(links, temp);
其中c:251是
strcat(links, temp);
and c:225 is my char *links = malloc(sizeof(char) * 100);
c:225是我的
char *links = malloc(sizeof(char) * 100);
am I using strcat wrong or what is the problem here? 我使用strcat错了吗?还是这是什么问题?
Memory you've got from malloc
isn't zero-initialized by default. 默认情况下,您从
malloc
获得的malloc
不是零初始化的。 And strcat
will append the new to the end of the string. 并且
strcat
会将新内容附加到字符串的末尾。 For non-zero-initialized chunk of memory that could be just anywhere. 对于非零初始化的内存块,该内存块可能随处可见。
You don't need to set the whole links
to zero -- just first byte would be enough. 您无需将整个
links
设置为零-仅第一个字节就足够了。 Still memset(links, 0, 100);
仍然
memset(links, 0, 100);
right after malloc
would not hurt. 在
malloc
之后不会受到伤害。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.