C - realloc() 函数 - 证明它会损坏数据
看看我用这个简单的代码发现了什么:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *string;
int main(){
string = (char *) malloc(50*sizeof(char));
strcpy(string, "initi1l wording cont2ining forty-nine ch3r4cters.");
printf("BEFORE: %s\n", string);
string = (char *) realloc(string, 24*sizeof(char));
printf("AFTER: %s\n", string);
system("PAUSE");
return 0;
}
输出是:
BEFORE: initi1l wording cont2ining forty-nine ch3r4cters.
AFTER: initi1l wording cont2inia
注意字符串末尾的“a”!我不知道它来自哪里,也许在堆的某个地方。它不是来自原始数据块。最初,我将 realloc() 与结构数组一起使用,它显然以更重要的方式破坏了数据。
我该如何解决这个问题?
Look what I found with this simple code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *string;
int main(){
string = (char *) malloc(50*sizeof(char));
strcpy(string, "initi1l wording cont2ining forty-nine ch3r4cters.");
printf("BEFORE: %s\n", string);
string = (char *) realloc(string, 24*sizeof(char));
printf("AFTER: %s\n", string);
system("PAUSE");
return 0;
}
The outpout is:
BEFORE: initi1l wording cont2ining forty-nine ch3r4cters.
AFTER: initi1l wording cont2inia
Notice it 'a' at the end of the string! I have no idea where this comes from, maybe somewhere in the heap. It is not from the original data block. Initially I was using realloc() with arrays of structures and it was obviously corrupting the data in more significant ways.
How can I work around this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
C 字符串需要
NUL
终止符。 您隐含地期望realloc()
以某种方式找出内存包含 C 字符串,并替换最后一个字符为NUL
。它不这样做;你必须自己做:换句话说,这是你的代码中的一个错误。
C strings require a
NUL
terminator. You're implicitly expectingrealloc()
to somehow figure out that the memory contains a C string, and replace its last character withNUL
. It doesn't do this; you have to do it yourself:In other words, it's a bug in your code.
事实并非如此!在 C 中,“字符串”是一组用 \0 分隔的字符。在这种情况下,您尝试打印“字符串”,因此您会得到原始的 24 个字符和一些尾部,直到在内存中找到随机 \0
It does not! In C "String" is a set of character delimited with \0. In this case you try to print "string", therefore you get your original 24 characters and some tail until random \0 is found in memory
C 中的字符串以 null 结尾。我很惊讶该程序没有崩溃。
Strings in C are null terminated. I am surprised that the program did not crash.
它是第 25 个字符,前 24 个字符中没有 0 终止符。
It's character 25 and you have no 0-termination in the first 24.