簡體   English   中英

使用帶有雙指針的malloc時出現段錯誤

[英]Getting seg fault when using malloc with double pointer

我正在使用像這樣的東西來分配帶有函數的內存(在C中)

void myfunction(struct mystruct** ss) {
    // some code
    *ss = malloc( 1024 * sizeof (struct mystruct) );
    // some code
}    
int main()
{
   struct mystruct **x;
   *x = NULL;
   myfunction(x);
   return 0;
}

但是我遇到了段錯誤。 此代碼有什么問題?

struct mystruct **x; ,變量x尚未初始化。 像程序在*x = NULL;那樣進行讀取是非法的*x = NULL;

您可能想寫:

int main()
{
   struct mystruct *x;
   x = NULL;
   myfunction(&x);
   return 0;
}

但是無法確定,因為您的程序沒有做任何有意義的事情。 注意, x = NULL; 無論如何都是不必要的: x將在myfunction()初始化。

您永遠不會為基礎指針進行任何存儲, **和對象而不是* ...有存儲。

struct mystruct **x,*y;
x = &y;
myfunction(x);
return 0;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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