realloc期间的分段错误

时间:2016-12-02 04:23:21

标签: c dynamic-memory-allocation

首先请允许我为格式化和困难的代码道歉。我是C和Stack的新手。这里的大多数混乱代码可能与问题无关,但必须包含在上下文中。

下面的代码在第一次调用realloc后会遇到分段错误(在注释中注明)。 return_file->target_line只是一个3D数组,i是3D数组第一维的元素数。所以我在其上调用realloc来存储额外的2D数组(类型为char **)。

故意省略了

NULL内存分配的返回b / c开发协议明确规定所有内存分配都会成功(我对此有疑问)。

我使用自己的记忆检查程序。我得到的错误代码是:

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7ac63fb in reallochook () from /lib64/libc.so.6

我已经看了很长时间,但似乎无法找到问题所在。

Mockfile *read_mockfile(const char filename[]) {
  Mockfile *return_file = NULL;
  FILE *input;

  if(filename != NULL && (input = fopen(filename, "r")) != NULL) {
    char **split_tmp, line[MAX] = {0};

    return_file = malloc(sizeof(Mockfile));
    return_file->rule_count = 0;

    /*read lines*/
    while(fgets(line, MAX, input) != NULL){
      if(line[0] != '#' && line[0] != '\n'){
        int j, i = return_file->rule_count;
        split_tmp = split(line);

        if(line[0] != '\t'){
          j = 0;


          /*target line. Realloc every string in three steps. Segementation fault occurs after this line below.*/
          return_file->target_line = realloc(return_file->target_line, (i + 1) * sizeof(char **));

          while(split_tmp[j] != NULL){
            return_file->target_line[i] = realloc(return_file->target_line[i], (j + 1) * sizeof(char *));
            return_file->target_line[i][j] = malloc(strlen(split_tmp[j]) + 1);
            strcpy(return_file->target_line[i][j], split_tmp[j]);
            j++;
          }
          return_file->target_line[i] = realloc(return_file->target_line[i], (j + 1) * sizeof(char *));
          return_file->target_line[i][j] = NULL;
        } else {
          j = 0;

          /*action line. Allocate every string in three steps*/
          return_file->action_line = realloc(return_file->action_line, (i + 1) * sizeof(char **));

          while(split_tmp[j] != NULL){
            return_file->action_line[i] = realloc(return_file->action_line[i], (j + 1) * sizeof(char *));
            return_file->action_line[i][j] = malloc(strlen(split_tmp[j]) + 1);
            strcpy(return_file->action_line[i][j], split_tmp[j]);
            j++;
          }
          return_file->action_line[i] = realloc(return_file->action_line[i], (j + 1) * sizeof(char *));
          return_file->action_line[i][j] = NULL;

          return_file->rule_count++;
        }
      }
    }
    fclose(input);
  }
  return return_file;
}

1 个答案:

答案 0 :(得分:5)

realloc()期望它的第一个参数指向一个有效的内存块或NULL,所以在malloc()后你应该初始化:

return_file = malloc(sizeof(Mockfile));
return_file->rule_count = 0;
return_file->target_line = NULL; /* Add this */

这应解决这次崩溃。

另请注意,foo = realloc(foo, N);是一个错误,因为realloc()可以返回NULL,因此您需要处理完整性。