Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A small yet weird <Segmentation Fault>

Tags:

arrays

c

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");
}
like image 611
user2899069 Avatar asked Dec 14 '25 03:12

user2899069


2 Answers

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].

like image 132
Doug T. Avatar answered Dec 15 '25 15:12

Doug T.


There are lots of problems in your code.

  1. int a[0]. You are defining an array of 0 elements. In C this will not work. You cannot do a[0]=1 since it will work only if a is an array of 1 or more elements.
  2. It gets worse with a[i]=*ptr. 2 problems here, as pointed above a[1], a[2], etc don't exist. and the second problem is you allocated ptr but assigning *ptr which might be having some garbage.

It is just the beginning.

like image 28
jaychris Avatar answered Dec 15 '25 17:12

jaychris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!