我在使用一个旨在成为String缓冲区的程序时遇到了一些麻烦,特别是这个函数用于使用字符串cstr重置缓冲区.如果cstr为null,则需要将内容重置为空char'\ 0'.它总是挂在第二组realloc,它正在调整大小buf->内容我不知道为什么会这样.任何帮助都是极好的.
结构:
typedef struct strbuf {
char *contents;
size_t length;
} StringBuffer;
Run Code Online (Sandbox Code Playgroud)
它被称为
strbuf_reset(sb, NULL)
Run Code Online (Sandbox Code Playgroud)
这是有问题的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) …Run Code Online (Sandbox Code Playgroud)