Search code examples
cdynamic-memory-allocation

memory reallocation in c


I am new very interested in c programming now i am writing a c program which for dynamically memory allocation.

These are the the stages of the program:

  1. it gets n numbers from user
  2. it prints them
  3. it gets another n numbers from the user
  4. it prints both sets of numbers

my program works fine for small values of n, but not for large ones, such as 200000 numbers. i.e first I entered 100000 numbers then I entered another 100000 numbers.

It executes fine for the first set but then it gives a segmentation fault. I use gdb for debugging. It shows SIGSEGV error.

Can anybody explain what happened and give me a solution for it?

#include<stdio.h>
#include<malloc.h>
int main(void)
{

    unsigned int *p=NULL;
    unsigned int n;
    unsigned int i;
    unsigned int *a;
    unsigned int *t;
    unsigned int k=0;

    printf("Enter no.of elements...");
    scanf("%d", &n);

    p = (unsigned int*)malloc(n*sizeof(unsigned int));
    a = p;
    t = p;
    for (i=0; i<n; i++, *p++, k++) {
        scanf("%d",p);
    }

    for(i=0;i<n;i++,a++) {
        printf("Element No-%d %d Address->%d\n", i, *a, a);
    }

    a=t;

    printf("next time...how many elements do you enter");
    scanf("%d",&n);

    t=p;
    a = (unsigned int*)realloc((void *)a, n*sizeof(int));
    for (i=0; i<n; i++, *t++ ,k++) {
        scanf("%d",t);
    }

    printf("next time...printing..\n");

    for (i=0; i<k; i++, a++) {
        printf("Element No-%d %d Address->%d\n",i,*a,a);
    }

    free(p);
    free(a);


}

Solution

  • realloc changes the size of the allocation, it doesn't grow the allocation by the size you specify.

    So you need to do

    a=realloc(a, original_size + extent_size);
    

    (You don't need to cast the return value of malloc or realloc in C.)

    Another note:

    t=p;
    ...
    a=t;
    ...
    t=p;
    a=realloc(...);
    

    You can't use t after the realloc, since realloc could have changed the block's address. Put t=a; after the realloc. (And use more descriptive names, your code is very hard to follow.)