#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/