[英]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似乎不正確。 我該怎么做?
其他答案推薦的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.