c - 添加动态变量时 C 列表的堆栈溢出

标签 c list stack-overflow dynamic-memory-allocation

我在学校项目中遇到一些问题。

我需要做的非常简单,我只需向列表中添加一些数据即可。 我通常知道如何做到这一点,但内存分配是动态的这一事实让我感到困惑。

这是列表:

typedef struct cList {
char *concept; // the concept learned
char *sentence; // the sentence associated with the concept
int timesUsed; //no of times the concept was used to an answer
char learnedFrom[5]; //learned either from "file" or "kbrd"
struct cList *next;
} conceptList;

以及将新数据添加到列表的函数:

void insert(char *concept, char *sentence, int timesUsed, char learnedFrom[5]) 
{
    int flag = 0, temp; 

    struct cList *link = (struct cList*) malloc(sizeof(struct cList));

    if(link!=NULL)
    {
        strcpy(link->concept,concept); //this is where the stack overflow happens first.
        strcpy(link->sentence,sentence);
        link->timesUsed = timesUsed;
        strcpy(link->learnedFrom,learnedFrom);

        link->next = head;
        head = link;

        temp = rand()%5;
        if(temp==0)
            printf("3B$ It sure is great to know everything about %s.\n", concept);
        else if(temp==1)
            printf("3B$ This information about %s is quite interesting.", concept);
        else if(temp==2)
            printf("3B$ I have to admit, learning about %s is much more interesting than it seems.", concept);
        else if(temp==3)
            printf("3B$ Learning about %s wasn't even a challenge.", concept);
        else if(temp==4)
            printf("3B$ Wow, learning about %s was so exciting!", concept);
    }
    else
        printf("3B$ Memory not available!!!\n");
}

最佳答案

第一次malloc之后,concept成员具有未初始化值。

之前需要为传递的字符串分配空间

strcpy(link->concept,concept);

所以你需要

link->concept = malloc(strlen(concept)+1);
if (link->concept != NULL)
{
    strcpy(link->concept,concept);
}
else
{
    free(link)
    return;
}

对于sentence成员来说也是如此。

关于c - 添加动态变量时 C 列表的堆栈溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44183081/

相关文章:

java - 如何在java中以表格格式显示linkedhashmap类型的列表

c - Socket C 同时处理 recv() 和 send()

c - 如何在C中取消初始化/dev/urandom的熵?

list - 列表的 WHILE 循环

java - 为什么在使用 Flood Fill 算法时会出现 java.lang.StackOverflowError?

delphi - 编译包含 TForm.Create(nil) 的 dwscript 时堆栈溢出

python - 处理Python中大计算的内存使用

c - C. 段错误中的十五局游戏

c - 将两个文件异或加密到第三个文件

list - 将两个输入的函数应用于列表中的每个元素 - Haskell