我有一个令人沮丧的问题,我找不到答案。
我有这个功能:
// 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;
}
在我创建 it_GetCharCmd() 并在那里使用它之前,AppendChar() 一直没有问题。我在这上面花了大约 3 个小时,但我找不到问题所在。在互联网上进行了一些搜索,但我发现的东西与我的问题并不完全相关。