[英]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;
聲明可能是破壞您的代碼的原因。 當您將其聲明為全局時,它存儲在 memory 中的不同位置,而不是在 function 中聲明它。
您很幸運讓您的程序將其作為全局變量使用。 由於您沒有在 memory 中保留任何位置,因此該變量正在訪問一些它不應該訪問的 memory(未定義的行為)。 幸運可能不是最好的形容詞,因為由於其未定義的行為,您可能認為您的程序工作正常,但事實並非如此(如果它崩潰了,您將 100% 認為有錯誤)。
您可以采取以下措施之一來解決這個問題:
動態分配它: char *str = (char*)malloc(sizeof(char)*25);
將其更改為 br 數組: char str[25];
指向現有數組: char arr[25]; char *str = arr;
char arr[25]; char *str = arr;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.