【发布时间】:2017-10-29 03:58:42
【问题描述】:
我的问题很简单,我不明白为什么这个程序不能正确输出:
int size = 35;
// malloc size for text
char *txt = malloc(size * sizeof(char *));
if(!txt) {
fprintf(stderr, "Allocation for text data failed.\n");
return EXIT_FAILURE;
}
for(int i = 0; i < size; i++) { // for each character in text
txt[i] = 'a';
}
printf("%s\n", txt);
free(txt);
预期输出:
呸呸呸呸呸呸呸呸
实际输出:
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa8 9 10 1 0 12 11 6 37 44 3 45 56 0 64 77 5 68 83 0 39 46 0 19 16 9 8 2 6 3 1 4 17 12 9 17 6 0 25 10 3 31 16 13 21 9 9 11 7 4 2 3 0 7 6 1 9 5 2 11 2 5 19 6 13 21 8 15 8 0 0 7 0 0 29 20 13 62 50 0 49 35 0 41 27 1 38 25 9 25 13 0 21 11 0 24
尝试使用valgrind --leak-check=yes 进行调试,它显示的唯一错误如下:
==3999== 条件跳转或移动取决于未初始化的值
==3999== 在 0x4C30F78:strlen(在 /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so 中)
==3999== 由 0x4EA969B: 放置 (ioputs.c:35)
==3999== by 0x400B39: main (decode.c:85) // 这是 printf 行
我以为是因为它不知道什么时候停止打印,但我尝试了:
while(txt != NULL) {
printf("%c", *(txt++));
}
我也试过了:
txt[size - 1] = '\0';
while((*txt) != '\0') {
printf("%c", *(txt++));
}
那些结果更糟,它会用特殊字符填充我的控制台。
【问题讨论】:
-
您似乎忘记了 C 中的
char字符串实际上称为 null-terminated 字节字符串。 null-termination 部分很重要。完成后,您可以将其打印为字符串。另请注意,这意味着 35 个字符的字符串需要 36 个字符的空间以适应终止符。 -
malloc(size * sizeof(char *));你想要 35 个字符,而不是 35 个字符指针。 -
哦,顺便说一句,
malloc(size * sizeof(char *))为size分配了足够的内存指针 到char。