c-当我声明这两个变量时,为什么我的程序崩溃了



我正在尝试使用C编程语言制作一个解释器,它运行良好,但当我试图在代码中添加这两个变量时,程序就会崩溃。幸运的是,当我在程序中添加static关键字或将变量保留为全局时,程序不会崩溃。为什么会发生这种情况?这是代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
//If I leave the variables here the program doesn't crash
//int esMain = 0;
//int esEnd = 0;
int main(int argc, char** argv){
FILE *f;
f = fopen(argv[1], "r+");

if(f == NULL){
perror("Error: No se encuentra el archivonDescripcion");
exit(1);
}
if(ferror(f)){
printf("Archivo corrupto");
exit(1);
}
printf("nEjecutando archivo: %snnn", argv[1]);

int esMain = 0;//These two variables makes the program to crash
int esEnd = 0;
//But if I add the static keyword in both variables the program works well.
char* str;
while(1){
fgets(str, 25, f);
if(strncmp(str, "MAIN:", 5) == 0){
esMain = 1;
}
if(strncmp(str, "END.", 4) == 0){
esEnd = 1;
}
if(feof(f) != 0){
if(esMain == 0){
printf("No existe el parametro main, cierre por no tener el parametro main (poner MAIN: ENCIMA)");
exit(1);
}
if(esEnd == 0){
printf("No existe el parametro end, cierre por no tener el parametro main (poner END. ENCIMA)");
exit(1);
}
break;
}
}
rewind(f);
while(1){
fgets(str, 500, f);
if(strncmp(str, "print ", 6) == 0){
printf(str + 6);
}
if(strncmp(str, "msg", 3) == 0){
if(strstr(str + 4, "check")){
MessageBox(HWND_DESKTOP, str + 10, "Check", MB_ICONINFORMATION);
}
if(strstr(str + 4, "error")){
MessageBox(HWND_DESKTOP, str + 10, "Error", MB_ICONERROR);
}
}
if(strncmp(str, "pause", 5) == 0){
getch();
}
if(feof(f) != 0){
break;
}

}
printf("nnnEND EXECUTION");
fclose(f);
return 0;
}

char* str;声明可能是破坏代码的原因。当您将其声明为全局时,它存储在内存中的不同位置,而不是在函数中声明它。

您有幸将您的程序作为全局变量使用它。由于您没有在内存中保留任何位置,因此变量正在访问一些不应该访问的内存(未定义的行为(Lucky可能不是最好的形容词,因为由于其未定义的行为,您可能会认为您的程序工作正常,但事实并非如此(如果它崩溃了,您将100%认为存在错误(。

你可以做什么来修复这是以下之一:

  1. 动态分配:char *str = (char*)malloc(sizeof(char)*25);

  2. 将其更改为br an array:char str[25];

  3. 指向现有阵列:char arr[25]; char *str = arr;

最新更新