首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >即使我在主内存中还有很多空间,realloc也会失败

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

Stack Overflow用户
提问于 2015-06-08 05:07:26
回答 1查看 40关注 0票数 1
代码语言:javascript
运行
复制
#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;
}

为什么我不能重新分配内存?(我的window操作系统上还有很多内存)当我运行这段代码时,malloc函数工作得很好,但realloc函数只工作了一次,第二次就失败了,所以我得到一个"reallocate base = ...“消息和6“重新分配失败基础= ...”消息

EN

回答 1

Stack Overflow用户

发布于 2015-06-08 05:13:51

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

使用:

代码语言:javascript
运行
复制
    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;
    }
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30698463

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档