正确使用 malloc 和 strcat 以避免 valgrind 出现内存错误
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
以“%d-%d”格式在临时中存储字符串,然后使用 strcat
将其与链接连接起来。
它确实可以正确打印所有内容,但是当我使用 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
获得的内存不是 zero-initialized。 strcat
会将新的追加到字符串的末尾。对于可能在任何地方的非zero-initialized内存块。
您不需要将整个 links
设置为零——只需第一个字节就足够了。在 malloc
之后仍然 memset(links, 0, 100);
不会受到伤害。
我已经在我的 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
以“%d-%d”格式在临时中存储字符串,然后使用 strcat
将其与链接连接起来。
它确实可以正确打印所有内容,但是当我使用 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
获得的内存不是 zero-initialized。 strcat
会将新的追加到字符串的末尾。对于可能在任何地方的非zero-initialized内存块。
您不需要将整个 links
设置为零——只需第一个字节就足够了。在 malloc
之后仍然 memset(links, 0, 100);
不会受到伤害。