Realloc分配的内存多于请求的内存

时间:2017-11-08 07:17:44

标签: c pointers dynamic-memory-allocation realloc

我遇到以下功能问题。

当我尝试realloc()记忆时,我得到的比实际要求的要多!

在这个例子中,我尝试连接两个字符串,一个长度为14个字符,一个长度为11个字符,但最终结果是memTemp长度为38个字符,即使memNewSize显示它实际上是25,有谁知道该怎么做?

int dstring_concatenate(DString* destination, DString source)
{
    assert(destination != NULL); // Precondition: destination ar ej NULL
    assert(*destination != NULL); // Precondition: *destination ar ej NULL
    assert(source != NULL); // Precondition: source ar ej NULL
    //Dstring looks like this = "typedef char* Dstring;"

    int memNewSize = strlen(*destination) + strlen(source);
    char *memTemp;
    memTemp = (char*)realloc(memTemp, sizeof(char) * memNewSize);

    printf("%d\n", memNewSize);
    printf("%d\n", strlen(memTemp));

    if(memTemp == NULL)
    {
        printf("Could not allocate new memory.\n");
        return 0;
    }
    else
    {
        *destination = memTemp;
        strcat(*destination, source);
        return 1;
    }
}

2 个答案:

答案 0 :(得分:6)

问题在于,realloc()仅适用<(em>正确)

    先前由allocator函数返回的
  • 指针
  • NULL指针。

引用C11,章节§7.22.3.5

  

如果ptr是空指针,则realloc函数的行为类似于malloc函数   指定size。否则,如果ptr与先前由内存返回的指针不匹配   管理功能,或者如果通过调用free或已释放空间   realloc函数,行为未定义。 [....]

在您的情况下,memTemp(作为自动存储本地范围变量)只是一个单元化指针,带有不确定值,指向谁知道 >地址!它甚至不能保证NULL。所以,你所拥有的只是undefined behavior

只是一个猜测:可能你打算用传入的memTemp初始化*destination

那就是说,正如实际问题中的评论所指出的那样,

  • realloc()中提供的大小乘数应为memNewSize + 1,以便能够容纳空终止符。
  • sizeof(char)保证在C中为1,因此将其用作乘数是多余的。

答案 1 :(得分:0)

好吧,我得到了它的工作,非常感谢你们!更新了以下代码。

int dstring_concatenate(DString* destination, DString source)
{
    assert(destination != NULL); // Precondition: destination ar ej NULL
    assert(*destination != NULL); // Precondition: *destination ar ej NULL
    assert(source != NULL); // Precondition: source ar ej NULL
    // Dstring look like this = "typedef char* Dstring;"

    int memNewSize = strlen(*destination) + strlen(source);
    char *memTemp;
    memTemp = (char*)realloc(*destination, sizeof(char) * memNewSize+1);

    if(memTemp == NULL)
    {
        printf("Could not allocate new memory.\n");
        return 0;
    }
    else
    {
        *destination = memTemp;
        strcat(*destination, source);
        return 1;
    }
}
相关问题