关于链表结构体释放内存问题,不太确定,谁能给个准确的说法的
最近在做编译器作业,写了个链表保存token,token的属性有type和content,两个都是指针,我动态创建的,但在释放时,一旦释放这两个指针,只能释放遍历开始时的第一个结点,释放第二个时就停住了,也点不了下一步,我一步步调试时发现每个结点的token属性的内存地址都不一样,为什么就不能全部释放,难道是释放结点时结点里的所有的东西都释放掉了?我记得结构体里存放指针只是一个地址,难道不需要把指针都释放掉吗?不是每malloc分配一次内存都要free一次吗?
结构体如下:
typedef struct Token
{
char *tokenType;
char *tokenContent;
struct Token *nextToken;
}Token;
sentence[i-1] = '\0';
strcpy(which, "note");
currentToken = (Token *)malloc(sizeof(Token));
currentToken->nextToken = NULL;
currentToken->tokenType = (char*)malloc(strlen(which));
strcpy(currentToken->tokenType, which);
currentToken->tokenContent = (char*)malloc(strlen(sentence));
strcpy(currentToken->tokenContent, sentence);
temp->nextToken = currentToken;
temp = temp->nextToken;
void Free()
{
Token *temp, *temp1;
temp = headToken;
while (temp != NULL)
{
//free(temp->tokenType);
//free(temp->tokenContent);
temp1 = temp->nextToken;
free(temp);
temp = temp1;
}
return ;
}
sentence[i-1] = '\0';
strcpy(which, "note");
currentToken = (Token *)malloc(sizeof(Token));
currentToken->nextToken = NULL;
currentToken->tokenType = (char*)malloc(strlen(which) + 1);//这里应该要+1吧。。还有最后的'\0'。。
strcpy(currentToken->tokenType, which);
currentToken->tokenContent = (char*)malloc(strlen(sentence) + 1);//这里也是。。
strcpy(currentToken->tokenContent, sentence);
temp->nextToken = currentToken;
temp = temp->nextToken;