【问题标题】:Realloc allocates more memory than requestedRealloc 分配的内存比请求的多
【发布时间】:2017-11-08 07:17:44
【问题描述】:

我对以下功能有疑问。

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

在这种情况下,我尝试连接 2 个字符串,一个是 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;
    }
}

【问题讨论】:

  • 当然标题应该是“realloc allocates too much memory”
  • 那为什么不编辑呢?
  • 什么是DString
  • 不应该是memNewSize + 1包含字符串终止符吗?
  • 至于你的问题,将*destination 传递给realloc 调用不是更有意义吗?

标签: c pointers dynamic-memory-allocation realloc


【解决方案1】:

这里的问题是,realloc() 仅在(正确)上工作

  • 分配器函数之前返回的指针
  • NULL 指针。

引用C11,第 7.22.3.5 章

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

在您的情况下,memTemp(作为自动存储局部范围的变量)只是一个未初始化的指针,具有 不确定值,指向 谁知道 地址!甚至不能保证是NULL。所以,你只有undefined behavior

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


也就是说,正如实际问题下的 cmets 所指出的那样,

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

【讨论】:

  • 您是否有用户脚本可以一键引用标准中的某个部分:p
  • @AjayBrahmakshatriya :) 不是真的,这只是我养成的一个坏习惯,以避免使用错误的措辞引起误解(英语不是我的母语,相信我,我曾经遇到过我写的东西是180度我的意思!!)
  • 嗨,Sourav,感谢您的快速回答! Dstring 是一个 typedef,它是一个 char 指针,所以 Dstring *destination 实际上是一个 char 双指针,并且 *destination 已经指向一个动态分配的字符串,所以如果我在 realloc() 调用中使用 *destination , memTemp 应该是一个问题吗?
  • @Erik.E 通常最好不要在 typedef 中隐藏指针
  • @Erik.E 不,如果我正确理解你的版本应该没有任何问题。
【解决方案2】:

好的,我搞定了,非常感谢大家!下面更新了代码。

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;
    }
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-07
  • 1970-01-01
  • 2020-07-01
  • 2021-03-16
  • 1970-01-01
  • 2016-07-04
相关资源
最近更新 更多