c - 即使我在主内存中还有很多空间,realloc 也会失败

标签 c

#include<iostream>
#include<algorithm>
#include<malloc.h>
#include<stdlib.h>
using namespace std;

typedef struct _intExpandArray{
    int size;
    int max;
    int *base;
} intExpandArray;

void addExpandArrayElement(intExpandArray *arr, int element){
    int *p;
    if(arr->base == NULL){
        arr->base = (int* )malloc(2*sizeof(int));
        arr->size = 0;
        arr->max = 2;
        cout<<"base = " << arr->base <<endl;
    }else if(arr->size >= arr->max){
        p = (int *)realloc(arr->base, arr->max*2*sizeof(int));
        if(p != NULL){
            cout<<"reallocate successful base = " << arr->base << endl;
            arr->max *= 2;  
        }else{
            cout<<"reallocate failed base = "<< arr->base <<endl;
        }
    }
    *(arr->base + arr->size) = element;
    arr->size++;
}

/* display array */
void dispIntExpandArray(intExpandArray arr){
    int i;
    int n = arr.size;
    int *p = arr.base;
    cout<< "size = " << n << " max size = " << arr.max << endl;
    for(i = 0; i < n; i++){
        cout<<p[i]<<" ";
    }
    cout<<endl;
}

int main(){
    intExpandArray arr;
    arr.base = NULL;
    int i = 0;
    for(i = 0; i < 10; i++){
        addExpandArrayElement(&arr, i);
        //dispIntExpandArray(arr);
    }
    return 0;
}

为什么我不能重新分配内存? (我的窗口操作系统上仍然有很多内存)当我运行这段代码时,malloc 函数工作正常,但 realloc 函数第一次工作,第二次失败,所以我得到一个“reallocate successful base = ...”消息和 6 条“重新分配失败基数 = ...”消息

最佳答案

在调用 realloc 后,您忘记重置 arr->base 的值。

使用:

    p = (int *)realloc(arr->base, arr->max*2*sizeof(int));
    if(p != NULL){
        arr->max *= 2;  
        arr->base = p; // Missing line
        cout<<"reallocate successful base = " << arr->base << endl;
    }else{
        cout<<"reallocate failed base = "<< arr->base <<endl;
    }

关于c - 即使我在主内存中还有很多空间,realloc 也会失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30698463/

相关文章:

c - 如何在 C exec.file 中找到构建的目录字符串?

c - 尝试打印结构元素,但结果为空白。 - C

c - 按升序排序整数数组,段错误 : 11

c++ - 为什么extern可以应用于定义?

coredump 重定向到文件

c++ - 如何在 C++ 绑定(bind)中使用不透明指针包装 C 库

c - 将函数指针分配给另一个函数内的函数

将 ZZ (NTL) 转换为 C 中的字符串

c - FTP 实现 : close data socket every time

c++ - 如何在 EXE 文件中找到要 Hook /绕行的函数地址?