首先讓我爲格式化和難度代碼道歉。我是C和Stack的新手。這裏大部分的混亂代碼可能與問題無關,但必須包含在上下文中。realloc期間的分段錯誤
在第一次調用realloc(註釋中註明)後,下面的代碼會出現分段錯誤。 return_file->target_line
只是一個3D數組,i
是3D數組第一維的元素數。所以我打電話realloc來存儲額外的二維數組(類型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;
}
@MD XF,你剛剛在談論大括號不在新行嗎? B/C這是我故意保留的個人偏好。 –
無論爲你工作......適合你。但是還有一些關鍵的改進,一些小的細節造成了很大的差異 –