【发布时间】:2023-02-02 19:18:26
【问题描述】:
我试图在 C 中实现链表,然后我决定实现相同的逻辑来创建一个“字符串”,本质上是具有更多功能的相同链表,主要是从输入字符串创建链表对象。当给定一个像 35 个字符的小输入字符串时,该代码工作得很好,但当输入字符串较大时,第一次运行 malloc 时会崩溃。现在我尝试在另一台机器上运行这段代码,它可以完美地处理任何大小的字符串(低于 1000 个字符),所以我怀疑我的机器有问题,原因是这些函数:
struct Map
{
char val;
struct Map *next;
};
void makeString(struct Map **head, char *needStr){
int i = 0;
while (needStr[i] != '\0'){
insert(head, needStr[i]);
i++;
}
}
void insert(struct Map **head, char value){
printf("%c", value);
if ((*head) == NULL)
{
(*head) = (struct Map *)malloc(sizeof(struct Map));
(*head)->val = value;
(*head)->next = NULL;
}
else
{
struct Map *cur = *head;
while (cur->next != NULL)
{
cur = cur->next;
}
struct Map *New = (struct Map *)malloc(sizeof(struct Map));
New->val = value;
New->next = NULL;
cur->next = New;
}
}
int main()
{
struct Map *list = NULL;
char *a = (char*) malloc(sizeof(char));
scanf("%[^\n]",a);
makeString(&string, a);
}
为了更直观地理解问题,这里有一个例子:
输入:
你好吗?
输出:
你好吗?
代码有效,运行在 main 中调用的所有其他函数。
输入: “****************************************************** ****************************************************** ****************************************************** *"
输出: “*”
vscode 指出插入函数内的 malloc 错误,它发生在第一次迭代中。
【问题讨论】:
-
您的真实代码是否没有对您调用的函数的前向声明?请尝试创建一个合适的minimal reproducible example 给我们看。
标签: c memory malloc heap-memory