You are here:

C/Storage location of a variable ?

Advertisement


Question
#include <stdio.h>

const int x=10;
int main()
{
/* Definition inside the function */
const int y = 20;
int *p, *q;

printf("\n x = %d", x);
printf("\n y = %d", y);

p= (int*)&x;
*p = 33; /* This reports Segmentation fault error- Why ? */

q=(int *)&y;
*q=44;     /* Works fine and doesnt report any error */

printf("\n x = %d", x);
printf("\n y = %d", y);

return 0;
}


Below are my 2 questions:

1) Can you please let me know where are the above variables x and y are stored ? (i,e in stack, data, or any )

2) Whats the different between those two - as one reports error when we try to change the value through pointer and other works well ?

Thanks
Ravi

Answer
Hello Ravi

I think the const int x is placed in a read only (text) part of the program. It probably depends on the compiler and operating system, but on my windows and visual studio compiler, it also causes a program abort. I suppose you are running on unix or linux if you are using the term segmentation fault.

The const int y is on the stack and so it can be changed. The compiler usually would not accept code to change y, but you cast its address as an int*, so you removed the const quality of the pointer.

The difference is that const x is put into a read only part of the program so the const quality is enforced by the compiler and the CPU. The const y is on the stack and so it's const quality is enforced by the compiler only.

I hope that helps you.

Best regards
Zlatko

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Zlatko

Expertise

No longer taking questions.

Experience

No longer taking questions.

Education/Credentials
No longer taking questions.

©2012 About.com, a part of The New York Times Company. All rights reserved.