簡體   English   中英

使用包含多個元素的結構的malloc

[英]Use of malloc of a struct containing multiple elements

我在這里做錯了什么?

我有一個QueueElement結構,其中包含char *文本和指向下一個元素的指針,因此很顯然是一個鏈表:

//QElement as in QueueElement
struct QElement {
    char* text;
    struct QElement* next;
};
typedef struct QElement QElement;

....

void enqueue (char* string){
QElement *new = (QElement *)malloc(sizeof(QElement)); 
//QElement cast is probably redundant but it doesn't hurt anyone
strcpy (new->text, string);

//some other stuff happening here, linking to other element in linked list, 
//but thats not of interest at the moment

}

....

如果嘗試在主函數中加入一個單詞,則會不斷出現分段錯誤,並且valgrind會告訴我,當我使用strcpy時我做錯了什么,因此我的malloc似乎不正確。 我該怎么做?

在這段代碼中

strcpy (new->text, string);

new->text未分配內存。 它可能包含一些垃圾值,或者一些寫保護的內存地址,甚至是NULL。 將該指針傳遞給strcpy()會導致您出現未定義的行為,並且作為副作用,您可能會遇到分段錯誤。

您可以使用strdup()或可以在將strcpy()指向該指針之前將內存分配給new->text 兩種情況下,您都需要在以后free()已分配的內存。

也,

  1. 不要 malloc()的返回值。
  2. 使用指針之前,請檢查動態內存分配[ malloc() / calloc() ]是否成功。

其他答案推薦的strdup(.)是非標准的。 如果您不在Unix平台上,則可能無法使用。

但是,這一點是正確的。 您需要分配內存來存儲您的字符串。

嘗試:

const size_t sz=(strlen(string)+1)*sizeof(*string);//Space required. Including '\0' terminator.
new->text=malloc(sz);//space allocated.
if(new->text==NULL){//sz never 0 because +1.
   exit(EXIT_FAILURE);//Allocation failed in non-error handled function.
}
memcpy(new->text,string,sz); //typically fastest way to copy!

代替strdup(.)

實際上,我不需要使用sizeof(*string) (因為它始終為1),但是編譯器會發現這一點,這只是一個好習慣。

有一天,世界將更加統一地遷移到多字節字符,並且這段代碼已經為光榮的黎明做好了准備!

完成“ QElement”操作后,不要忘記free(.) 您可能應該編寫這樣的函數:

void QElementDestroy(QElement*const element){
    if(element==NULL){
        return;//Nothing to do!
    }
    free(element->text);//Needs NULL protection.
    free(element);//Does not need NULL protection. But we've done the test anyway!
    //NB: Order matters here. A lot.
}

並在完成enqueue(.)返回的值后調用它。

如果您希望字符串“不活躍”,則在調用destroy之前將元素設置為element->text=NULL free(NULL)是不執行任何操作並正常返回的要求。

PS:我認為strdup(.)有點n00b陷阱。 他們花了一些時間才能匹配malloc(.)free(.)strdup(.)有點叛徒,因為其他str...函數都沒有分配調用者期望free(.)空間free(.) 這也是非標准的。

因為您只為結構變量分配內存。 您必須在結構成員中分配內存。

 new->text=malloc(10);//for example 

分配內存后,可以使用strcpy函數。

您已為new分配了內存,但沒有為text成員變量分配內存。 text分配內存並執行代碼。

暫無
暫無

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

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