如何知道字符串指针在重新分配后是否真的变小了?

How to know if a string pointer actually got smaller after realloc?

我在字符串上使用 realloc() 使其 size/memory 更小,这样我就丢失了 end.I 中具有空字符 '\0' 的字节,然后放回去新的更小字符串的空字符。

我知道检查字符串大小的方法是 funtcion strlen(),但是 strlen 会在发现空字符时停止。

所以问题是我真的释放了 space 还是 strlen 只是停在我手动设置的空字符上 end.How 我可以检查吗?

很好奇,你怎么看我的post这么快?

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

char * function ()
{
    int number;
    char *string;

    printf("Give number: ");
    scanf("%i",&number);

    string = (char *) calloc(256,sizeof(char));

    printf("Give string: ");
    scanf("%s",string);

    string = (char *) realloc(string,number+1);//I make the string smaller

    string[number] = '[=10=]';//I set the null at the end of the new size

    return string;
}

int main()
{
    char *string;

    string = function();

    printf("Size of string is: %i\n",strlen(string));//I check the size of string
    puts(string);

    return 0;
}

你不能 "double-check" realloc 如果这是你的问题

The standard defines realloc 的行为,如果它未能提供您要求的连续字节数,它将 return NULL.

现在,realloc 实际使用了多少字节?内存管理函数的内部是实现定义的,但实际上您使用的是 page size 的倍数,通常是 4KiB。棘手的部分是您不知道 realloc 将您放在页面的哪个位置,因此您不能依赖它。

询问您需要的字节数,您不会出错。不要假设内存管理功能提供的功能比您要求的要多,并且该标准保证您至少拥有您需要的功能。

这里有多个问题需要考虑:

  • realloc() returns 块的地址 至少 如果成功则请求的大小,否则 returns 一个空指针。如果调用失败,将此 return 值直接存储到传递的指针中将用空指针覆盖此指针,从而无法使用原始指针,即使只是释放它也是如此。

  • scanf() 应传递最大字节数以读入数组,即您的示例中的 255。

  • 您应该测试 scanf() 的 return 值以检测无效输入并避免在出现此类故障时使用未设置变量的未定义行为。

  • 您应该测试 number 是否为阳性。将负值传递给 realloc() 将请求大量内存,导致调用失败。

  • 如果你知道最大字符串长度,你可以在读取字符串之前分配正确的大小。

  • 关于你的问题:如果数字小于256,而你读到的字长超过number字节,设置string[number] = '[=16=]';必要的 截断字符串,因为 realloc() 只是将数组缩短为 number+1 字节,可能会移动内容,但会保留偏移量 number.

    [=44 处的字节=]