小编Eri*_*k.E的帖子

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

c pointers realloc dynamic-memory-allocation

0
推荐指数
1
解决办法
170
查看次数

标签 统计

c ×1

dynamic-memory-allocation ×1

pointers ×1

realloc ×1