gpt4 book ai didi

c - Malloc 的段错误

转载 作者:行者123 更新时间:2023-11-30 15:26:58 25 4
gpt4 key购买 nike

我今天需要为我的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com