[英]C struct program crash
嗨我試圖學習CI中的數據結構寫一個程序,但它運行時崩潰
#include <stdio.h>
#include <stdlib.h>
typedef struct{
int x;
int y;
}structure;
typedef struct{
structure test1;
}test;
void function(test *trying){
trying->test1.x = 5;
printf("%d\n", trying->test1.x);
}
int main(){
test *mystruct;
function(mystruct);
system("pause");
return 0;
}
謝謝!
test *mystruct;
function(mystruct);
mystruct
指針未初始化並具有不確定的值。
由於缺少初始化,此語句調用未定義的行為:
trying->test1.x = 5;
這樣做:
test mystruct;
function(&mystruct);
當你編寫test *mystruct;
, mystruct
包含垃圾值 。 如果此值位於程序的地址空間之外,則會出現錯誤。 為何崩潰? 因為它試圖覆蓋OS等受保護的內存區域。 因此要么為mystruct
分配內存並使用它(在這種情況下你必須釋放內存)。 或者普通聲明為普通變量並將地址傳遞給函數。
test mystruct;
function(&mystruct);
您可以使用此答案的后半部分,但正如其他評論者所指出的那樣,將mystruct
的地址簡單地傳遞給函數會mystruct
。
test mystruct; // = (test *) malloc(sizeof(test));
function(&mystruct);
這意味着它在堆棧上分配,這與堆不同,並且您在使用它之后不必釋放內存,因為它已經為您完成了。
如果要將其聲明為指針,則可以在堆上分配內存以進行test
。
更改你的第一線main
以:
test *mystruct = malloc(sizeof(test));
並釋放使用它后分配的內存:
free(mystruct);
在函數main
,變量mystruct
未初始化為指向有效的內存地址。 因此,它很可能指向無效的內存地址,並且當在函數function
使用時,它最終會產生內存訪問沖突。
修正建議#1:
test mystruct;
function(&mystruct);
修正建議#2:
test* mystruct = malloc(sizeof(test));
function(mystruct);
free(mystruct);
如果你不想使用動態內存,那么試試這個:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
int x;
int y;
}structure;
typedef struct{
structure test1;
}test;
void function(test *trying){
trying->test1.x = 5;
printf("%d\n", trying->test1.x);
}
int main(){
test mystruct;
memset(&mystruct, 0, sizeof(mystruct));
function(&mystruct);
system("pause");
return 0;
}
這將創建一個基於堆棧的變量,並使用memset()
函數初始化其內容。 你有一個奇怪的中間typedef和成員,你可以完全消除。 例如
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct my_s{
int x;
int y;
} my_t;
void function(my_t *t){
if(!t) return;
t->x = 5;
printf("%d\n", t->x);
}
int main(){
my_t mystruct;
memset(&mystruct, 0, sizeof(mystruct));
function(&mystruct);
return 0;
}
最后,我不確定你要用系統完成什么(“暫停”)但是對於結構,上面的例子將起作用。
嘗試對原始代碼進行這些簡單的更改:( 不使用malloc()
或calloc()
構建和運行)
(在線評論解釋)
#include <stdio.h>
#include <stdlib.h>
typedef struct{
int x;
int y;
}structure;
typedef struct{
structure test1;
}TEST; //use CAPITALS to distinguish typedefed struct for readability
TEST test; //use typedef to create instance of TEST
void function(TEST *trying){
trying->test1.x = 5;
printf("%d\n", trying->test1.x);
}
int main(){
TEST *mystruct; // create local instance of TEST
mystruct = &test;//initialize mystruct pointer to point to beginning of physical struct
function(mystruct);
system("pause");
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.