是否realloc的覆盖旧的内容? [英] Does realloc overwrite old contents?

查看:214
本文介绍了是否realloc的覆盖旧的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们通过重新分配内存的realloc(),都是previous内容过写的?我试图做一个程序,每一个我们将数据输入到它的时间重新分配内存。

When we reallocate memory via realloc(), are the previous contents over-written? I am trying to make a program which reallocates memory each time we enter the data into it.

请通过realloc的告诉我的内存分配,它是编译器相关的,例如?

Please tell me about memory allocation via realloc, is it compiler dependent for example?

推荐答案

不要担心旧的内容。

正确的方法使用的realloc 是用于重新分配一个特定的指针,测试指针,如果一切工作正常,改变旧的指针

The correct way to use realloc is to use a specific pointer for the reallocation, test that pointer and, if everything worked out ok, change the old pointer

int *oldpointer = malloc(100);

/* ... */

int *newpointer = realloc(oldpointer, 1000);
if (newpointer == NULL) {
    /* problems!!!!                                 */
    /* tell the user to stop playing DOOM and retry */
    /* or free(oldpointer) and abort, or whatever   */
} else {
    /* everything ok                                                                 */
    /* `newpointer` now points to a new memory block with the contents of oldpointer */
    /* `oldpointer` points to an invalid address                                     */
    oldpointer = newpointer;
    /* oldpointer points to the correct address                                */
    /* the contents at oldpointer have been copied while realloc did its thing */
    /* if the new size is smaller than the old size, some data was lost        */
}

/* ... */

/* don't forget to `free(oldpointer);` at some time */

这篇关于是否realloc的覆盖旧的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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