[英]Why does my C program crash when i add any statement to the main function?
我对 C 相当陌生 - 我制作了一个程序,它读取一个文本文件,并通过几个函数使用malloc()
和realloc()
处理文本并格式化输出。 目前我的main()
只有以下内容:
1. 初始化结构
line_arr.max_size = 0;
line_arr.num_lines = 0;
line_arr.line = NULL;
Word_Array word_arr;
word_arr.max_size_ = 0;
word_arr.num_words = 0;
word_arr.word = NULL;
Word_Array ex_words;
ex_words.max_size_ = 0;
ex_words.num_words = 0;
ex_words.word = NULL;
Line_Array.line
和Word_Array.word
都是指向Line
和Word
结构的指针。 Line 和 Word 是包含一个 char 数组和一个 int 的结构体,用于跟踪行号或单词出现的行号。
2.调用处理输入文本文件的函数
get_lines(&line_arr, argv[1]);
get_words(&line_arr, &word_arr);
sort_keywords(&word_arr);
我的所有函数都返回void
。
所有的输出和格式都发生在函数和我有malloc
的任何空间中,我随后没有任何错误地释放了它。 该程序生成所需的输出,但是如果我向main()
添加任何语句,甚至是打印语句,我都会收到bus10
错误或segmentation fault 11
错误。
我已经尝试过 gdb,但我以前没有使用过它,而且当我尝试运行该程序时,gdb 似乎挂起并冻结了。
我想知道是否有人知道为什么会这样? / 是否有一些我不了解 C 或malloc()
基本逻辑?
感谢您的专业知识!
编辑结构:
typedef struct Line Line;
struct Line{
char line[MAX_LINE_LEN];
};
typedef struct Word{
char word[MAX_WORD_LEN];
int line_number;
}Word;
typedef struct Word_Array{
//will point to the base in memory where the list of words begins.
Word *word;
int max_size_;
int num_words;
}Word_Array;
typedef struct Line_Array{
//line is a variable that stores an address of a line object.
Line *line;
int max_size;
int num_lines;
}Line_Array;
get_lines()
:
void get_lines(Line_Array *la, char const *filename){
Line *line_ptr;
char *buffer;
size_t buffer_len;
FILE *fp = fopen(filename, "r");
if(fp == NULL){
printf("Can't read file. \n");
exit(1);
}
while (getline(&buffer, &buffer_len, fp) > 0) {
buffer[strlen(buffer)-1] = '\0';
if (la->line == NULL) {
la->line = (Line *) malloc(sizeof(Line));
if (la->line == NULL) {
exit(1);
}
la->max_size = 1;
la->num_lines = 0;
}
else if (la->num_lines >= la->max_size) {
line_ptr = (Line *) realloc(la->line, (2*la->max_size) * sizeof(Line));
if (line_ptr == NULL) {
exit(1);
}
la->max_size *= 2;
la->line = line_ptr;
}
strncpy(la->line[la->num_lines].line, buffer, MAX_LINE_LEN);
la->num_lines++;
}
fclose(fp);
}
自从我稍后使用它以来,我没有释放此方法中的内存,但是即使没有运行其他函数,也会存在同样的问题,如果我在调用 get_lines 之前或之后向 main 添加某些内容,我会收到总线 10错误作为我唯一的输出。 但是,如果我只调用get_lines()
和其他函数,程序会产生正确的输出。
至少有一个问题:
//char *buffer;
//size_t buffer_len;
char *buffer = NULL;
size_t buffer_len = 0;
笔记:
在while (getline(...
, code should free with free(buffer);
strncpy(la->line[la->num_lines].line, buffer, MAX_LINE_LEN);
不保证la->line[la->num_lines].line
是string 。 为什么 strncpy 不安全?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.