114k views
2 votes
I have a statement int *p = 10; . This statement executes perfectly fine on any compiler. I also know that 10 is put in read-only memory. Is there a way i can access this memory. How can I print this on console? The statement printf("%d",*p) crashes. How can I make it print on console.

Edit

int main()
{
int *p = 10;
}
the above code compiles fine and runs fine.

int main()
{
int *p = 10;
printf("\\%d",*p); //crashes
}
the above code gives segmentation fault. I wanted to know more explanation on this?

User Jlovison
by
8.2k points

1 Answer

6 votes

Final answer:

The statement int *p = 10; assigns the pointer p to an invalid memory address, causing a segmentation fault. It should instead point to a valid integer variable, like int value = 10; int *p = &value; which is then safe to dereference and print.

Step-by-step explanation:

The statement int *p = 10; in C does not do what you might intuitively expect. It sets the pointer p to the address 10 in memory, which is not a valid location for the program to access, hence resulting in a crash or segmentation fault. If you want to assign the value 10 to a location in memory and then print it, you should use the following code:

int main() {
int value = 10;
int *p = &value;
printf("%d", *p); // prints 10
return 0;
}
Here, p points to the address of variable value, which contains the integer 10. The printf function can then safely dereference p to print its value.

User Oskar Grosser
by
7.9k points