[英]Correct use of malloc and strcat to avoid memory errors with valgrind
我已经在tempStorage中存储了顶点:
typedef struct {
int pred[8];
int succ[8];
} arc_set;
arc_set tempStorage;
例如.pred是0,1,1,2,2和.succ是2,2,3,3,1
我做了一个char *links = malloc(sizeof(char) * 100);
存储这些数字并像这样打印它们:
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");
使用sprintf
然后使用带有链接的strcat
concat将temp格式的字符串存储为“%d-%d”格式。
它确实可以正确打印所有内容,但是当我用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)
其中c:251是strcat(links, temp);
c:225是我的char *links = malloc(sizeof(char) * 100);
我使用strcat错了吗?还是这是什么问题?
默认情况下,您从malloc
获得的malloc
不是零初始化的。 并且strcat
会将新内容附加到字符串的末尾。 对于非零初始化的内存块,该内存块可能随处可见。
您无需将整个links
设置为零-仅第一个字节就足够了。 仍然memset(links, 0, 100);
在malloc
之后不会受到伤害。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.