C - realloc() 函数 - 证明它会损坏数据

发布于 2024-12-12 13:24:03 字数 662 浏览 0 评论 0原文

看看我用这个简单的代码发现了什么:

#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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

谁把谁当真 2024-12-19 13:24:03

C 字符串需要 NUL 终止符。 您隐含地期望 realloc() 以某种方式找出内存包含 C 字符串,并替换最后一个字符为 NUL。它不这样做;你必须自己做:

string = (char *) realloc(string, 24*sizeof(char));
string[23] = 0;   // <========= THE FIX
printf("AFTER: %s\n", string);

换句话说,这是你的代码中的一个错误。

C strings require a NUL terminator. You're implicitly expecting realloc() to somehow figure out that the memory contains a C string, and replace its last character with NUL. It doesn't do this; you have to do it yourself:

string = (char *) realloc(string, 24*sizeof(char));
string[23] = 0;   // <========= THE FIX
printf("AFTER: %s\n", string);

In other words, it's a bug in your code.

自控 2024-12-19 13:24:03

事实并非如此!在 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

雨夜星沙 2024-12-19 13:24:03

C 中的字符串以 null 结尾。我很惊讶该程序没有崩溃。

Strings in C are null terminated. I am surprised that the program did not crash.

窝囊感情。 2024-12-19 13:24:03

它是第 25 个字符,前 24 个字符中没有 0 终止符。

It's character 25 and you have no 0-termination in the first 24.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文