Aadesh Magare
Aadesh Magare

Reputation: 47

Dynamic Memory allocation in C : Problems in Realloc

I have this problem regarding the use of malloc and realloc. I've searched a lot and found many similar questions but couldnt find any satisfying answer.

This is a simple code which gives problem at realloc it prints numbers till 2999 and then some error comes. Can anyone plz explain me whats wrong

Sorry for repost but i couldnt find any clear answer

#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;
}

Upvotes: 0

Views: 357

Answers (1)

MahlerFive
MahlerFive

Reputation: 5289

You are only sending size to realloc, but you need to multiply size by sizeof(int) as you did in your call to malloc.

Upvotes: 1

Related Questions