【问题标题】:Infinity getchar with reallocation具有重新分配的无限 getchar
【发布时间】:2022-10-13 17:27:45
【问题描述】:

嗨,我正在尝试让控制台读取字符并使用 realloc 增加大小,直到我点击 ctr+z 并结束循环。终端显示分段错误。如何解决这个问题?

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


int main()
{
    int size = 2;
    char* buffer = NULL;
    buffer = (char*) malloc(size*sizeof(char));
    if(buffer==NULL)
    {
        puts("Allocation failed");
    }

    printf("Enter character: ");
    while(1)
    {
        buffer = getchar();
        size++;
        buffer = (char*) realloc(buffer,size*sizeof(char));
         if(buffer==NULL)
    {
        puts("Allocation failed");
    }
    }
    
}

【问题讨论】:

  • 缓冲区 = getchar();应该给你编译器警告...... getchar() 返回一个 int 并且这会破坏指向分配的堆内存的指针......你想要某种索引或其他东西将字符放入缓冲区,而不是猛击缓冲区地址...

标签: c


【解决方案1】:

而不是这个:

buffer = getchar();

这个:

*buffer = getchar();

但是您还应该支持在重定向输入的情况下检测 EOF:

while(1)
{
    int result = getchar();
    if (result == EOF)
    {
        break;
    }
    *buffer = (char)result;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-28
    • 2022-01-11
    • 2016-04-13
    • 1970-01-01
    • 2021-05-13
    • 2013-10-15
    • 2014-09-14
    • 1970-01-01
    相关资源
    最近更新 更多