动态大小字符数组中的运行时错误

时间:2017-04-11 20:50:37

标签: c

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

int main(void) {
  int i = 0;
  char c, *input;
  input = (char *) malloc(sizeof(char));

  if(input == NULL) {
    printf("NOT ENOUGH SPACE!");
    exit(1);
  }

  printf("Input a string, press ENTER when done: ");

  while((c = getchar()) != '\n') {
    realloc(input, (sizeof(char)));
    input[i++] = c;
  }

  input[i] = '\0';
  printf("\nYou've entered the string: %s\n", input);
}

以上代码段适用于小输入。但只要提供的输入量很大,它就会失败。存在运行时错误或分段错误。 重新分配内存空间时可能会出现一些错误。 我基本上想要从用户动态存储一个字符数组,即没有提到用户可以直接放入任何大小的字符数组的输入容量。

1 个答案:

答案 0 :(得分:2)

这里的逻辑是错误的:

  while((c = getchar()) != '\n') {
      realloc(input, (sizeof(char)));
      input[i++] = c;
  }

您实际上并没有增加缓冲区的大小,而且您也放弃了realloc的结果。

尝试:

  while ((c = getchar()) != '\n') {
    // Note: you need one extra character for the terminator, so for the
    // first char, when `i` is 0, then you need room for two `char`s in
    // the buffer - one for the first input character and one for the
    // terminator. And so on...
    char * temp = realloc(input, i + 2); // NB: realloc can, and sometimes does, fail
    if (temp == NULL) // if realloc failed then exit program
        exit(1);
    input = temp;     // otherwise update input...
    input[i++] = c;
  }

<小时/> 此外,因为你总是会在每个角色上调用realloc(这是非常低效的,顺便说一句,但它有效),这一行:

input = (char *) malloc(sizeof(char));

(不应该有一个演员,BTW,因为这是C,而不是C ++)可以只是:

input = NULL;

<小时/> 最后一个错误:

char c;

应该是:

int c;

否则您的while循环可能永远不会终止,因为EOF只能正确表示为int

<小时/> 所以最终的固定程序应该是这样的:

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

int main(void) {
    int i = 0;
    int c;
    char * input = NULL;

    printf("Input a string, press ENTER when done: ");

    while ((c = getchar()) != '\n') {
        // Note: you need one extra character for the terminator, so for the
        // first char, when `i` is 0, then you need room for two `char`s in
        // the buffer - one for the first input character and one for the
        // terminator. And so on...
        char * temp = realloc(input, i + 2); // NB: realloc can, and sometimes does, fail
        if (temp == NULL) // if realloc failed then exit program
            exit(1);
        input = temp;     // otherwise update input...
        input[i++] = c;
    }

    input[i] = '\0';
    printf("\nYou've entered the string: %s\n", input);

    return 0;
}