簡體   English   中英

使用Malloc的分段錯誤

[英]Segmentation Fault with Malloc

今天,我需要為我的CS類實現特定的ADT strqueue,因此我編寫了兩個函數:create_StrQueue()和add_to_back(StrQueue sq,const char * str)。 不幸的是,當我在add_to_back中調用create_StrQueue時,出現了段錯誤,並且我無法弄清楚為什么。 這是我為這兩個函數編寫的代碼:

[edit]我可能應該在add_to_back中分配tempWord。

#include <stdlib.h>

// A strqueue is an ADT consisting of words
struct strqueue{
  StrQueue back;    // last StQueue in queue
  StrQueue next;    // next StrQueue in queue

  char* word;       // stored string
  int length;       // length of entire queue
};

typedef struct strqueue* StrQueue;

StrQueue create_StrQueue(void){

  StrQueue retq = malloc(sizeof(struct strqueue));  // get memory for a new strqueue
  retq->word = malloc(sizeof(char*)); 
  retq->word = NULL;
  retq->back = retq;       // set back pointer to itself
  retq->next = NULL;       // nothing after this strqueue yet

  return retq;
}

void add_to_back(StrQueue sq, const char* str){

  char* tempWord;
  sq->length++;

  for(int i=0; str[i]; ++i) tempWord[i]=str[i];  // copy string for the new strqueue

  if(sq->word==NULL) sq->word = tempWord;  // input strqueue was empty

  // input StrQueue was not empty, so add a new StrQueue to the back
  StrQueue new = create_StrQueue(); // results in seg fault
  new->word = tempWord;
  sq-back->next = new;  // swaping pointers around to add malloced StrQueue to the back
  sq->back = next;
}

我很茫然,所以我希望有人能弄清楚到底發生了什么,因為當我像這樣運行main時;

int main(void){

char* str1 = "Hello";

StrQueue sq = create_StrQueue(); // does not cause seg fault
add_to_back(sq, str1);
}

第一次調用create_StrQueue()效果很好。

結構中的char*是指向字符數組的指針。 retq->word = malloc(sizeof(char*)); 不是分配字符串的正確方法; 這實際上是在 word 分配一個很小的數組 ,實際上是無用的,然后您通過為word分配NULL來覆蓋剛分配的內容,從而泄漏內存。 malloc分配的所有內存必須稍后使用free手動釋放。 您正在處理一個指針。 向其分配數據沒有C的魔力,您只需替換指針本身的值即可。

add_to_back ,需要在將數據復制到tempWord之前為其分配空間:

tempWord = malloc( strlen(str)+1 );

您添加1以容納字符串中的空終止符。 使用strcpy復制到tempWord而不是在那里編寫自己的字符串復制方法,該方法不會添加空終止符。

更好的解決方案是讓create_StrQueue接受const char*參數,然后在其中進行字符串分配和復制。

您還應該避免使用“ new ”一詞,因為這會使C ++程序員感到困惑。 :)

暫無
暫無

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

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