我正在制作一个程序将文件拆分成lexemes但我不熟悉C而且我得到一个奇怪的分段错误.以下代码运行并打印:
1
2
Segmentation Fault: 11
Run Code Online (Sandbox Code Playgroud)
我查找了其他导致分段错误的原因,我在2之后没有对数组做任何事情.我做错了什么?简单的分配如何导致分段错误?
#include <stdio.h>
#define CHAR_CODE 1
#define NUM_CODE 2
#define RESERVED_CHAR_CODE 3
#define SPACE_CODE 4
#define ERR_CODE 5
char token[16];
char line[128];
int lineLen = 0;
int counter = 0;
FILE *file;
void cleanToken(){
for(int i = 0 ; i < 16; i++){
token[i] = 0;
}
}
void cleanLine(){
for(int i = 0 ; i < 128; i++){
line[i] = 0;
}
}
void next(){
cleanToken();
printf("1\n");
char c;
if(counter == lineLen){
printf("2\n");
lineLen = 0;
printf("3");
cleanLine();
printf("4");
counter = 0;
while((c=getc(file)) != 10 && c != EOF){
if(c!=32){
line[lineLen] = c;
lineLen++;
}
printf("%d\n", lineLen);
}
printf("%s\n", line);
}
c = line[counter];
int type = getType(c);
while(getType(c)==type){
token[counter] = c;
counter = counter + 1;
c = line[counter];
if(c == EOF | c == 4 | type == RESERVED_CHAR_CODE){
break;
}
}
}
int getType(int c){
if((c > 96 & c < 123) | (c>64 & c < 91)){
return CHAR_CODE;
} else if(c < 58 & c > 46){
return NUM_CODE;
} else if(c == 32){
return SPACE_CODE;
} else if(c == 33 | c == 34 | (c > 36 & c < 44) | c == 45 | c == 47 | (c > 58 & c < 63)){
return RESERVED_CHAR_CODE;
} else {
return ERR_CODE;
}
}
int main(){
int c;
FILE* file;
file = fopen("test.txt", "r");
for(int i = 0; i < 10 ;i++){
next();
printf("%s\n", token);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
您的代码中存在许多问题,其中大部分问题将-Wall在编译时使用,但具体而言,崩溃是由于尝试访问file尚未初始化的全局变量引起的.
你main()用另一个具有相同名称的变量将其遮蔽了.您初始化了那个,但没有被访问的全局next().
此外,您的printf语句不足以进行调试,因为无法保证在程序崩溃之前将输出缓冲区刷新到控制台.如果添加\n到printf("3") and printf("4")行中,您将看到它们在崩溃之前被打印.或者,您可以在通话fflush(stdout)后printf()打电话以确保打印它们.通过执行此操作,您将看到崩溃不会因显示的分配而发生.
这样的调试器gdb在调试代码时非常有用.