【发布时间】:2025-12-12 12:25:03
【问题描述】:
我正在学习链表,我不明白释放字符串时的行为变化。代码如下:
#include <stdio.h>
#include <stdlib.h>
struct node {
char* data;
struct node* next;
};
void Push(struct node** headRef, char *data)
{
struct node* newNode = malloc(sizeof(struct node));
newNode->data = data;
newNode->next = *headRef; // The '*' to dereferences back to the real head
*headRef = newNode; // ditto
}
int main(int argc, const char * argv[])
{
char* auxStr;
struct node* list;
struct node* auxPtr;
int i=5;
while (i<9)
{
auxStr=malloc(sizeof("String:%d"));
sprintf(auxStr, "String:%d",i);
Push(&list, auxStr);
i++;
}
auxPtr=list;
i=0;
while (auxPtr)
{
printf("Node:%d - Data:%s\n",i++,auxPtr->data);
auxPtr=auxPtr->next;
}
return 0;
}
结果:
Node:0 - Data:String:8 Node:1 - Data:String:7 Node:2 - Data:String:6 Node:3 - Data:String:5
现在,当我第一次添加 free(auxStr) 时:
while (i<9)
{
auxStr=malloc(sizeof("String:%d"));
sprintf(auxStr, "String:%d",i);
Push(&list, auxStr);
free(auxStr);
i++;
}
我现在明白了:
Node:0 - Data:String:8
Node:1 - Data:String:8
Node:2 - Data:String:8
Node:3 - Data:String:8
有人可以解释为什么吗?我知道它可能不是最有效的代码释放多次,但我看到了这种行为,这让我感到困惑。感谢您的帮助,帮助我更好地理解这个概念。
谢谢
【问题讨论】:
-
请注意,当您的整数变为
>= 100时,malloc(sizeof("String:%d"))的缓冲区对于sprintf()来说太小了。
标签: c pointers linked-list malloc free