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

Why my program crashes when I declare this two variables?

我正在尝试使用 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 archivo\nDescripcion");
    exit(1);
}

if(ferror(f)){
    printf("Archivo corrupto");
    exit(1);
}

printf("\nEjecutando archivo: %s\n\n\n", 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("\n\n\nEND EXECUTION");

fclose(f);

return 0;
}

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

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

您可以采取以下措施之一来解决这个问题:

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

  2. 改成数组:char str[25];

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