我已经在我的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
存储格式为“%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错了吗,或者这是什么问题?
答案 0 :(得分:1)
您从malloc
获得的内存在默认情况下不会初始化为零。 strcat
会将新内容附加到字符串的末尾。对于非零初始化的内存块,该内存块可能随处可见。
您不需要将整个links
设置为零-仅第一个字节就足够了。 memset(links, 0, 100);
之后的malloc
仍然不会受到伤害。