繁体   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