减少重新分配 [英] Decreasing realloc

查看:52
本文介绍了减少重新分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个关于理解的问题realloc 行为.

I have a few questions about understanding realloc behavior.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int *str;

    /* Initial memory allocation */
    str = malloc(5 * sizeof(int));
    *str = 1;
    *(str + 1) = 2;
    *(str + 2) = 3;
    *(str + 3) = 4;
    *(str + 4) = 5;

    /* Reallocating memory */
    int i, j;

    for (i = 5; i > 0; i--) {
        str = realloc(str, i * sizeof(int));

        for (j = 0; j < i; j++) {
            printf("%d", *(str + j));
        }  

        printf("\n");
    }

    free(str);

    return(0);
}

  1. 在这个代码示例中,我能确定较小的 realloc 会丢弃最高的数字吗?

  1. In this code example, can I be sure that a smaller realloc will drop the highest number?

realloc 是否只释放最后一块内存并在 str 中保持相同的地址?或者即使地址变小并且当前位置肯定有空间,地址也可能会改变?

Is the realloc is only freeing the last memory and keeping the same address in str? Or may the address change even though it's getting smaller and for sure have space in the current place?

推荐答案

  1. 是的.如果您有一个大小为 N 的内存块 p 并且您执行了 realloc(p, M),那么(假设 realloc 成功),结果将包含 p 的前 min(N, M) 个字节.

  1. Yes. If you have a memory block p of size N and you do realloc(p, M), then (assuming realloc succeeds), the result will contain the first min(N, M) bytes from p.

地址可以改变,即使新的大小比旧的小.realloc 根本不保证这种情况(它甚至可能失败).

The address can change, even if the new size is smaller than the old one. realloc simply makes no guarantees about this case (it can even fail).

这篇关于减少重新分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆