c语言 - 为什么终端在运行程序时报告"zsh: trace trap"错误?


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *line = NULL;
size_t linecap = 0;
int main(int argc, char *argv[]) {
FILE *fp_in = fopen(argv[1], "r");
if (fp_in == NULL) {
printf("error: cannot open file '%s'n", argv[1]);
exit(1);
}
// two files are the same.
if (!(strcmp(argv[1], argv[2]))) {
printf("Input and output file must differn");
exit(1);
}
ssize_t length;
FILE *fp_out = fopen(argv[2], "w");
char *lines = (char *) malloc(1);
while ((length = getline(&line, &linecap, fp_in)) > 0) {
lines = (char *) realloc(lines, sizeof(lines) + length * sizeof(char));
strcat(line, lines);  //make lines behind the new line
strcpy(lines, line);  // turn the new string back into lines
}
fprintf(fp_out, "%s", lines);
free(lines);
fclose(fp_in);
fclose(fp_out);
return 0;
}

代码是读取一个文件的内容并反转其行顺序,然后写入另一个文件
执行后,shell发出:
zsh:trace trap
有人能给我解释一下吗?谢谢

您的核心问题是这个

lines = (char *) realloc(lines, sizeof(lines) + length * sizeof(char));

CCD_ 1和CCD_

你可以做

lines = (char *) realloc(lines, strlen(lines) + strlen(line) + 1);

因为两者都是0终止的

相关内容

  • 没有找到相关文章

最新更新