C中的realloc()问题.总是挂起但编译得很好

Dea*_*ean 3 c buffer pointers memory-management realloc

我在使用一个旨在成为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)
   buf->contents = '\0';
else
   strcat(buf->contents,cstr);

buf->length = strlen(buf->contents);    

return buf;
 }
Run Code Online (Sandbox Code Playgroud)

我相信建议的变化......

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;
 }
Run Code Online (Sandbox Code Playgroud)

Ano*_*on. 7

你似乎不明白是什么realloc.

应该考虑它的方式(至少就扩大而言)是它分配一个新缓冲区,将旧数据复制到其中,然后释放旧缓冲区.

然后旧指针无效,如果您在以后尝试再次使用它时遇到崩溃,则不应该感到惊讶.

您应该立即将返回的值分配回旧指针,因此它仍然指向有效数据.