我有一个令人沮丧的问题,但找不到答案。
我有这个功能:
// Append character to the end of a string
void str_AppendChar(char* s, const char* ch)
{
// +2 because of 2x '\0'
char* buff = malloc(strlen(s)+strlen(ch)+2);
memset(buff, 0, sizeof(buff));
// Copy the whole string in buff
strcpy(buff, s);
// Append ch at the end of buff
int len = strlen(buff);
strcpy(buff+len, ch);
// Set end of the string
*(buff+strlen(buff)-3) = '\0';
strcpy(s, buff);
free(buff);
}
由于某种原因,我的程序尝试在最后执行两次 free。
我使用 AppendChar() 的代码是:(有点难看,但请耐心等待)
void it_GatherCmd(cmd_Details* lineptr[], char* cmd)
{
// Used to count number of rows in lineptr
int nlines;
Detailptr p;
char ch;
char* word = (char*)malloc(sizeof(char)+256);
memset(word, 0, sizeof(word));
nlines = 0;
while ((ch = *cmd++) != '\n')
{
if (ch != ' ' && ch != '\0' )
str_AppendChar(word, &ch);
else
{
int type = dict_CheckWord(word);
if (type != -1)
{
p = it_CopyInfo(word, type);
lineptr[nlines++] = p;
}
memset(word, 0, sizeof(word));
}
}
//EDIT*
free(word);
}
我的主要内容:
int main()
{
cmd_Details* arrCmd[MAXLINES];
char* str = "just some string";
it_GatherCmd(arrCmd, str);
printf("%s", str);
return 0;
}
AppendChar() 工作正常,直到我创建 it_GetCharCmd() 并在那里使用它。我花了大约3个小时来解决这个问题,但我找不到问题所在。在互联网上进行了一些搜索,但我发现的内容与我的问题并不完全相关。
最佳答案
这段代码有一些问题。
首先,如果 str_AppendChar
正如其名称所暗示的那样,实际上附加了一个字符,那么为什么要给它一个暗示 C 字符串的 const char*
呢?此处传递指针而不是实际对象的增益为零,就像某些结构体的情况一样;实际上,您仍然需要将 4 个字节压入堆栈。
其次,正如我在评论中指出的那样,问题是您没有正确初始化分配的缓冲区 - sizeof(buff)
返回良好,buff 的大小和 buff 是a char*
这很可能是 4。只需将 sizeof(buff)
更改为 strlen(s)+strlen(ch)+2
,这是您实际分配的内存量解决了问题(并且由于 sizeof(buff)
可能超过了您实际分配的内存,因此您正在写过去的内存),我建议简化函数如下:
// Append character to the end of a string
void str_AppendChar(char* s, char ch)
{
size_t sLen = strlen(s);
char* buff = (char*)malloc(sLen + 2); // 1 for the appended char, 1 for \0
//memset(buff, 0, sLen + 2); //not necessary, we'll overwrite the memory anyway
// Copy the whole string in buff
strcpy(buff, s);
// append our char and null-terminate
buff[sLen] = ch;
buff[sLen + 1] = '\0';
strcpy(s, buff);
free(buff);
}
请注意,这段代码仍然很糟糕;它很高兴地假设 s 将足够大以容纳一个额外的字符,但情况并非总是如此。
还有关于你的 it_gatherCmd 函数;它应该采用 const char* ,因为它不会以任何方式修改它(事实上,您调用它的方式,您给它一个 const char* ;修改字符串文字是未定义的行为,在 Windows 上您可能会因违反页面权限而崩溃)。
关于c - 不应该出现两次 free(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30274245/