AnkurVj
AnkurVj

Reputation: 8198

Why do I get a segmentation fault if I print the contents of this memory location

Suppose I do the following

int *p = 1;
printf("%d", *p);

I get a segfault. Now, as I understand it, this memory location 1 is in the address space of my program. Why should there be a problem in reading this memory location ?

Upvotes: 2

Views: 113

Answers (5)

Sparky
Sparky

Reputation: 14057

To answer this properly will really depend upon a number of factors. However, it is quite likely that the address 0x00000001 (page 0) is not mapped and/or read protected.

Typically, addresses in the page 0 range are disallowed from a user application for one reason or another. Even in kernel space (depending upon the processor), addresses in page 0 are often protected and require that the page be both mapped and access enabled.

EDIT: Another possible reason is that it could be segfaulting is that integer access is not aligned.

Upvotes: 3

iehrlich
iehrlich

Reputation: 3592

No, address 1 is not in the address space of your program. You are trying to access a segment you do not own and receive segmentation fault.

Upvotes: 2

Kerrek SB
Kerrek SB

Reputation: 477030

Your pointer doesn't point to anything valid. All you do is assign the value 1 to a pointer-to-int, but 1 isn't a valid memory location.

The only valid way to obtain an pointer value is either take the address-of a variable or call an allocation function:

int a;
int * p1 = &a; // OK
int * p2 = malloc(sizeof(int));  // also OK

*p1 = 2;
*p2 = 3;

As for "why there should be a problem": As far as the language is concerned, if you dereference an invalid pointer, you have undefined behaviour, so anything can happen -- this is really the only sensible way to specify the language if you don't want to introduce any arbitrary restrictions, and C is all about being easy-to-implement.

Practically, modern operating systems will usually have a clever virtual memory manager that needs to request memory when and as needed, and if the memory at address 1 isn't on a committed page yet, you'll actually get an error from the OS. If you try a pointer value near some actual address, you might not get an error (until you overstep the page boundary, perhaps).

Upvotes: 4

K-ballo
K-ballo

Reputation: 81349

Your operating system won't let you access memory locations that don't belong to your program. It would work on kernel mode though...

Upvotes: 2

Kurtis Nusbaum
Kurtis Nusbaum

Reputation: 30825

You're trying to print 1, not the memory location. 1 isn't a valid memory location. To print the actual memory location do:

printf("%p", p);

Note the %p as icktoofay pointed out.

Upvotes: 1

Related Questions