[英]Dynamic Memory allocation in C : Problems in Realloc
我對使用malloc和realloc有這個問題。 我已經搜索了很多,發現了許多類似的問題,但是找不到任何令人滿意的答案。
這是一個簡單的代碼,在重新分配時會出現問題,它會打印數字直到2999,然后出現一些錯誤。 誰能解釋我怎么了
抱歉重新發布,但我找不到明確的答案
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char *argv[]){
int *a, i, j, *b;
long int size = 300;
a = (int *)malloc(sizeof(int) * size);
if(a == NULL){
printf("malloc failed\n");
exit(1);
}
for(i = 0; i < 100000; i++){
if( i >= size){
size = size * 10;
a = (int *)realloc(a, size);
if(a == NULL){
printf("realloc failed\n");
exit(1);
}
}
a[i] = i;
printf("%d\n", a[i]);
}
return 0;
}
您只發送size
到realloc
,但是需要像調用malloc
一樣將size
乘以sizeof(int)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.