我在学校项目中遇到一些问题。
我需要做的非常简单,我只需向列表中添加一些数据即可。 我通常知道如何做到这一点,但内存分配是动态的这一事实让我感到困惑。
这是列表:
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/