我在使用旨在作为字符串缓冲区的程序时遇到了一些问题,特别是此函数旨在使用字符串 cstr 重置缓冲区。如果 cstr 为 null,则需要将内容重置为空字符 '\0'。它总是挂在第二组 realloc 上,它正在调整 buf->contents 的大小,我不知道为什么会这样。任何帮助都是极好的。
结构:
typedef struct strbuf {
char *contents;
size_t length;
} StringBuffer;
它被称为
strbuf_reset(sb, NULL)
这是有问题的 strbuf_reset 函数。
StringBuffer *strbuf_reset(StringBuffer *buf, const char *cstr)
{
if(buf == NULL)
return NULL;
StringBuffer *tempBuf = NULL ;
if(cstr == NULL)
tempBuf = (StringBuffer*)realloc(buf,sizeof(StringBuffer) + sizeof(char));
else
tempBuf = (StringBuffer*)realloc(buf,sizeof(buf) + strlen(cstr)*sizeof(char));
if(tempBuf == NULL)
return NULL;
if(cstr == NULL)
tempBuf->contents = (char*)realloc(buf->contents,sizeof(char));
else
tempBuf->contents = (char*)realloc(buf->contents,(sizeof(buf->contents) + strlen(cstr)*sizeof(char) + 1));
if(tempBuf->contents == NULL){
free(tempBuf);
return NULL;
}
buf = tempBuf;
if(cstr == NULL)
buf->contents = '\0';
else
strcat(buf->contents,cstr);
buf->length = strlen(buf->contents);
return buf;
}
我认为建议的更改是……
StringBuffer *strbuf_reset(StringBuffer *buf, const char *cstr)
{
if(buf == NULL)
return NULL;
StringBuffer *tempBuf = NULL ;
if(cstr == NULL)
tempBuf = (StringBuffer*)realloc(buf,sizeof(StringBuffer) + sizeof(char) + 10);
else
tempBuf = (StringBuffer*)realloc(buf,sizeof(buf) + strlen(cstr)*sizeof(char)+ 1);
if(tempBuf != NULL)
buf = tempBuf;
else
return NULL;
if(cstr == NULL)
tempBuf->contents = (StringBuffer*)realloc(buf->contents,sizeof(StringBuffer) + sizeof(char) + 10);
else
tempBuf->contents = (StringBuffer*)realloc(buf->contents,sizeof(buf) + strlen(cstr)*sizeof(char)+ 1);
if(tempBuf != NULL)
buf->contents = tempBuf->contents;
else
return NULL;
if(cstr == NULL)
buf->contents = '\0';
else
strcat(buf->contents,cstr);
buf->length = strlen(buf->contents);
return buf;
}