【问题标题】:does the pointer reallocate memory as it increments?指针在增加时会重新分配内存吗?
【发布时间】:2021-04-15 04:02:24
【问题描述】:

如何阻止 *str 填充我没有给它的内存,而不必添加结束条件,在这种情况下是:i

do{
   //instructions;
} while (... && i <= n);

在这个例子中,我只为 *str 保留了 3 个字节 的内存,但是当我运行我的代码并输入超过 3 个字符时,它仍然可以工作......如何发生这种情况不应该给出错误,因为其余字符没有足够的内存吗?如果选择的空地址是 xxxxx1 xxxxx2 xxxxx3 然后 xxxxx4 已满,它会停止并仅输出 3 个字符而不会出错? P.s:我知道函数 gets() 但我不想使用它,因为它会重新分配内存。我认为通过逐个字符输入我将解决问题并阻止用户填充指针,因为这次没有内存重新分配并且 *str 只有 3 个内存块,所以其余的会去到缓冲区,*str 将停在 *(str + 2) 希望您理解问题并感谢您的回答

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

int main()
{
    int i = -1, n = 3;
    char *str = (char *)malloc(n*sizeof(char));

    printf("Enter a string: ");
    do
    {
        i++;
        str[i] = getchar();
    } while (str[i] != '\n' && i < n);

    str[i] = '\0';

    printf("Entered string is: %s", str);
    return 0;
}

【问题讨论】:

  • 您可能需要查看可以指定大小的 fget,它不允许填充比分配更多的空间。 fgets(str, n, stdin); 在这种情况下,您不需要循环。

标签: c pointers memory-management malloc realloc


【解决方案1】:

C 不对数组或分配的内存执行任何类型的边界检查。这是让它快速的部分原因。

这也意味着读取或写入数组末尾会导致undefined behavior,这基本上意味着无法保证程序会做什么。语言相信你会做正确的事,所以你有责任确保你不做你不应该做的事情。

另外,gets 不会重新分配内存。事实上,根本不应该专门使用它,因为它不执行任何边界检查。

【讨论】:

    【解决方案2】:

    如果输入字符串长于两个字符,则您的示例不起作用,因为它会尝试写入数组之外的内容。当您尝试在数组外部写入时会发生什么是未定义的,这意味着它在某些情况下可能纯属偶然。试试这个安全函数,它总是读取整行并在必要时截断结果:

    #include <assert.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    void ReadLine(char result[], int resultLen)
    {
        int ch, i;
    
        assert(resultLen > 0);
    
        i = 0;
        ch = getchar();
        while ((ch != '\n') && (ch != EOF)) {
            if (i < resultLen - 1) {
                result[i] = ch;
                i++;
            }
            ch = getchar();
        }
        result[i] = '\0';
    }
    
    
    int main(void)
    {
        int n = 3;
        char *str = malloc(n);
    
        printf("Enter a string: ");
        ReadLine(str, n);
        printf("Entered string is: %s\n", str);
        free(str);
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2012-08-10
      • 2015-12-24
      • 1970-01-01
      • 2020-09-18
      • 1970-01-01
      • 2022-09-24
      • 1970-01-01
      • 1970-01-01
      • 2018-08-20
      相关资源
      最近更新 更多