我需要重新分配通过scanf("%ms", ...)
获取的字符串,realloc
是否自动包含终止符\0
在我重新分配的字符串中?在这种情况下,realloc
的行为是什么?
它会在重新分配的字符串末尾添加\0
,还是将\0
保留在前一个字符串的相同位置,并在之后添加未初始化的内存\0
?
例如:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
char *string = NULL;
char *p = NULL;
int length = 0;
//This should automatically add \0 at the end, if i'm not wrong
scanf("%ms", &string);
length = strlen(string);
p = realloc(string, sizeof(char) * (length + 10));
if (p != NULL) {
string = p;
p = NULL;
}
free(string);
return 0
}
PS:我在字符串上使用了strlen()
,如下所示:strlen with scanf("%ms"...)
最佳答案
realloc
不知道/关心空字节或给定对象中存储的任何其他内容。它只是保证旧内容被保留/复制到它返回的新对象中(假设 realloc 调用成功)。只要您之前添加过它,它就会在 realloc
之后出现。在您的情况下,空字节在那里(假设 scanf
成功),所以它也会在 realloc
之后在那里。
但是,请注意,如果您使用 realloc
缩小对象,则只会保留指定大小的内容 - 在这种情况下,您可能没有realloc
之后的空字节。
关于c - realloc 是否在重新分配的字符串中包含\0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51765591/