0

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;
}
1
  • 8
    You forgot to multiply by sizeof *a (plus: you don't want the cast) Commented Aug 15, 2014 at 13:35

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.