realloc 是否在重新分配的字符串中包含 \0?

does realloc include \0 in reallocated string?

我需要重新分配通过 scanf("%ms", ...) 获取的字符串,realloc 会自动在我重新分配的字符串中包含终止符 [=13=] 吗? realloc在这种情况下的行为是什么?

它会在重新分配的字符串末尾添加 [=13=],还是将 [=13=] 保留在前一个字符串的相同位置,在 [=13=] 之后添加未初始化的内存?

例如:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main() {
    char *string = NULL;
    char *p = NULL;
    int length = 0;
    //This should automatically add [=10=] 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(),如下所示:

realloc() 不仅适用于字符或整数。它会自动释放之前的内存分配,然后重新分配请求的内存。

Will it add [=11=] at the end of the reallocated string?

这是不可能的。

Will it leave the [=11=] in the same position of the previous string, adding uninitialized memory after [=11=]?

realloc() 不会覆盖旧内容,不会覆盖之前的内存位置。它不会触及它的内容,只是移动到并重新分配新的内存块。

realloc 不会 know/care 关于空字节或给定对象中存储的任何其他内容。它只是保证旧内容 preserved/copied 在新对象中 returns (假设 realloc 调用成功)。只要您之前添加过它,它也会在 realloc 之后出现。在你的情况下,空字节在那里(假设 scanf 成功),所以它也会在 realloc 之后出现。

但是,请注意,如果您收缩 realloc 的对象,那么只会保留指定大小的内容 - 在这种情况下,您可能realloc.

后没有空字节

realloc() - 更改 ptr 指向的内存块的大小。

内存块的内容将保留到新旧大小中较小的一个,即使该块被移动到新位置也是如此。如果新大小更大,则新分配部分的值为indeterminate.

您需要为字符串分配内存,在使用realloc()之前使用malloc()。 scanf() 将无法将内存写入 NULL 指针(字符串值)。