Why i am getting Segfault in below program for pointer but not for array?

79 views Asked by At

1.

int a=3,*p=&a;
p++;
*p=10;

Then it is giving segmentation fault.

2.

int a[3]={1,2,3};
a[10]=10;

Then it is working properly

2

There are 2 answers

0
Spikatrix On

Both code snippets exhibit Undefined Behavior.

In both the code snippets, you write into an invalid memory location invoking Undefined Behavior. Anything can happen when you do it. It needn't necessarily segfault or crash. It might work one time, but fail when you do it the next time.

0
Seema Kadavan On

Both the code snippets can result in undefined behavior.

For the first one,

int a=3,*p=&a;
p++;
*p=10;

You have allocated memory for int a, assume its 4 bytes. then 'p' points to starting address of 'a'. When you do 'p++', since 'p' is of type int*, it increments by size of int. '*p' points to the location (address of a + size of int), which is not allocated. Hence it segmentation faults.

Assuming size of int is 4, your allocation almost looks like this (Haven't considered endianess here).

| 0x00 | 0x00 | 0x00 | 0x03 | <Not allocated> | <Not allocated>

When you did p++, p points to the first byte.

In second case, you are just lucky enough that it didn't give seg fault. You have allocated only (3 * size of int) bytes of memory and trying to access a[10], which is not allocated. It might give you a segmentation fault or will return you any garbage value.