c - 为什么从控制台读取字符并存储在数组中时出现段错误?

标签 c arrays memory-management segmentation-fault dynamic-memory-allocation

我正在尝试编写一个程序,将字符从标准输入读取到字符数组中,这样我就可以对该数组执行其他操作。我编写程序在需要时为数组动态分配更多内存。但是,一旦我结束程序的输入,我总是会遇到段错误。

注意事项:

  • 我使用 int 而不是 char 来存储正在读入的字符,所以我认为与 EOF 的比较应该有效?
  • ch == 'l' 行就在那里,因为我厌倦了按两次 Ctrl+D,一旦我解决了这个问题,它就会被删除。

下面是main内部,stdlib/stdio#included在程序开头:

int arrCount = 0, arrSize = 200, ch, key_data_len;
char* input = malloc(arrSize * sizeof(char));

printf("Input is an array of %d characters that takes up %d bytes.\n", arrSize, arrSize * sizeof(char));

// Add characters to array until input is finished.
while ( (ch = (int) getchar()) != '\0' && ch != EOF) {
  if(arrCount >= arrSize)
  { 
    printf("GOT IN IF STATEMENT.");
    // If the array has not been initialized, fix that.
    if (arrSize == 0)
      arrSize = 200 * sizeof(char);

    // Make the reallocation transactional by using a temporary variable first
    char *_tmp = (char *) realloc(input, (arrSize *= 2));

    // If the reallocation didn't go so well, inform the user and bail out
    if (!_tmp)
    {
      fprintf(stderr, "ERROR: Couldn't realloc memory!\n");
      return(-1);
    }

    // Things are looking good so far
    input = _tmp;
  }

  printf("\narrCount = %d; ch = %c; sizeof(ch) = %d\n", arrCount, ch, sizeof(ch));
  input[arrCount++] = ch;

  printf("&input[%d] = %p\n", arrCount-1, &input[arrCount - 1]);
  printf("input[%d] = %c\n", arrCount - 1, input[arrCount - 1]);
  if (ch == 'l') {
    break;
  }
}

示例输出:

... $ ./db

Input is an array of 200 characters that takes up 200 bytes.

tl

arrCount = 0; ch = t; sizeof(ch) = 4

&input[0] = 0x827a008

input[0] = t

input[0] = t


arrCount = 1; ch = l; sizeof(ch) = 4

&input[1] = 0x827a00a

input[1] = l

input[1] = t

Segmentation fault

可能与此相关的其他事情:我注意到如果我为我的输入数组输入足够的字符以达到索引 399/大小 400,也会弹出此错误:

*** glibc detected *** ./db: realloc(): invalid old size: 0x08a73008 ***

最佳答案

这是错误的,您正在释放刚刚分配的数组:

input = _tmp;
free(_tmp);

您根本不需要 free - realloc 会为您完成。

关于c - 为什么从控制台读取字符并存储在数组中时出现段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12433229/

相关文章:

c - 函数什么时候必须通过引用接收参数才能改变参数的某些内容?

不能和可以更新字符串指针变量

sql - 如何从 postgresql 的数组中排除?

javascript - 将数学应用于数组中的值

c# - Java是否允许直接内存访问

C:使用=(等于)复制指针数据

用C计算文件中的单词

c - 一个数组的最后一个元素被下一个数组的第一个元素覆盖

java - Android 堆转储转换为 J2SE : hprof-conv: command not found

java - java中的参照物是什么?