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:
- it gets
nnumbers from user - it prints them
- it gets another
nnumbers from the user - 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);
}
reallocchanges the size of the allocation, it doesn’t grow the allocation by the size you specify.So you need to do
(You don’t need to cast the return value of
mallocorreallocin C.)Another note:
You can’t use
tafter the realloc, since realloc could have changed the block’s address. Putt=a;after the realloc. (And use more descriptive names, your code is very hard to follow.)