I am not very experienced with C memory concepts. I tried searching for a solution, but could not find one.
I am just trying to create dynamic array in C. I tried to create it in this way while trying to check whether the addresses are contiguous. The program ran fine.
However, I got a segmentation fault after the statement system("pause"). I also tried to debug using the debugger, with no luck! I'm using Dev CPP.
Can anybody guide me?
#include<stdio.h>
#include<stdlib.h>
main()
{
int a[0], *ptr, i;
printf("%d", sizeof(a[0]));
a[0]=1;
for(i=1;i<10;i++)
{
ptr=(int *) malloc(sizeof(int));
printf("Enter a[%d]: ", i);
a[i]= *ptr;
scanf("%d", &a[i]);
}
i=0;
while(i<10)
{printf("\n%u", &a[i++]);}
free(ptr);
system("pause");
}
int a[0]
doesn't have any space allocated to it (its 0 width)
Yet you write to it on this line:
a[0]=1;
You also assume it has 10 elements here:
while(i<10)
{printf("\n%u", &a[i++]);}
free(ptr);
Practically speaking, as this is just stack memory, you're just writing to another piece of the stack. You could, for example, be overwriting the value of ptr. Often this can go undetected until the stack is unwound and part of it is apparently corruptted. Here the stack is unwound right after system("pause"), when main returns.
(Also, if ptr is overwritten by your writes to a you can't be sure that free does anything reasonable.)
To allocate a 10 integer array, use the syntax:
int a[10];
Then you can use a[0] up to a[9]. But this is C don't expect anything to protect you when you try to read/write to a[10].
There are lots of problems in your code.
It is just the beginning.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With