簡體   English   中英

C struct程序崩潰

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM