c - Malloc 的段错误

标签 c queue malloc abstract-data-type

我今天需要为我的 CS 类(class)实现特定的 ADT strqueue,因此我编写了两个函数:create_StrQueue() 和 add_to_back(StrQueue sq, const char* str)。不幸的是,当我在 add_to_back 中调用 create_StrQueue 时,出现了段错误,并且我无法确切地弄清楚原因。这是我为这两个函数编写的代码:

[编辑]我可能应该在 add_to_back 中 malloc 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 ,基本上没用,然后你通过分配 NULL 覆盖刚刚分配的内容至word ,泄漏内存。由 malloc 分配的所有内存稍后必须使用 free 手动释放。您正在处理一个指针。在 C 语言中,向其分配数据并没有什么魔力,您只需替换指针本身的值即可。

add_to_back ,在将数据复制到其中之前,您需要为 tempWord 分配空间:

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

添加 1 以容纳字符串中的空终止符。使用strcpy复制到tempWord您的方法不会添加空终止符,而不是在那里编写您自己的字符串复制方法。

更好的解决方案是让 create_StrQueue 接受 const char*参数,并在其中进行字符串分配和复制。

您还应该避免使用“new”这个词因为对于 C++ 程序员来说这看起来有点令人困惑。 :)

关于c - Malloc 的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27236295/

相关文章:

c - 打印 MAC 地址时出现问题

检查输入是否为数字

Java 队列并发

c++ - 如何跨 DLL 边界跟踪内存

c - 使用 memcpy 时出现 "pointer being freed was not allocated"

c - 对二维数组使用 MPI 散点图

c - 使用 extern 关键字的链接出现 undefined reference 错误

java - 是否有任何 Java 库提供随机访问队列实现?

c++ - std::queue pop 推送线程安全

c - 从文本文件中读取未知长度的字符串并打印它们