我已经寻找了这个问题的答案,但到目前为止还没有找到任何东西来回答这个特定的问题,所以在这里提问.
我有一些C代码,它动态地为字符串分配空间,并复制位于局部变量中的缓冲区的内容.然后,这个动态分配的字符串存储在一个 struct 中,并在程序的其他地方使用.
现在,当我完成 struct 时,我试图成为一个好公民并释放字符串,然而,当我这样做时,没有失败,程序崩溃了.就我所知,我传入了指向free()的正确指针,如果省略了对free()的调用,那么我已经确认内存泄漏了,那么我做错了什么?
以下是代码的要点.
typedef struct Token {
size_t length;
const char* lexeme;
// Other members
} Token;
// Original string is stored in a stack allocated static buffer:
static char buffer[1024];
// ... stuff here to fill buffer
// Then we generate the dynamic copy of the buffer contents
char* formattedMessage = realloc(NULL, sizeof(char) * strlen(buffer));
// Token is dynamically allocated as needed:
Token* token = realloc(NULL, sizeof(Token));
token->lexeme = strcpy(formattedMessage, buffer);
token->length = strlen(formattedMessage);
// ... Then we do other stuff (which all works, the message is stored in the struct and all is well)
// When we're done we call:
token->lexeme = free((void*)(token->lexeme));
// Which is where the program crashes.
请注意,在实际代码中,我测试了Token-&>lexeme是否为指向字符串的有效指针,并在跟踪时判断内存转储,结果显示传递给Free()的地址是该字符串的正确地址.
在这里撕裂我的头发.