c - C 中 realloc() 的问题。总是挂起但编译正常

标签 c memory-management pointers buffer realloc

我在使用一个旨在成为字符串缓冲区的程序时遇到了一些问题,特别是此函数旨在使用字符串 cstr 重置缓冲区。如果 cstr 为空,则需要将内容重置为空字符“\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;
 }

最佳答案

你似乎不明白realloc 的作用。

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

然后旧指针无效,如果您稍后尝试再次使用它时发生崩溃,这并不奇怪。

您应该立即将返回值分配回旧指针,这样它仍然指向有效数据。

关于c - C 中 realloc() 的问题。总是挂起但编译正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3137157/

相关文章:

iOS:当应用程序进入后台调用电话时,如何防止启动画面显示?

c# - 将指针数组转换为 IntPtr 数组

c - 填充和打印二维数组

c - 当我们将一个结构复制到另一个结构时的互斥行为

c - 这是缓冲区溢出的示例吗?

iphone - 使 UIViewController 中的 NSTimer 无效以避免保留周期的最佳时间

c++ - 如何创建一个函数,它以任意函数指针作为参数?

C 代码指针谜题

无法使用 C 语言将 'void*' 类型转换为 'double*' 或 'float*'

c - 如何使用 ARM Cortex A9 中的 SWI 来使能 IRQ 中断?