-1

Here is the code

#include <stdio.h>

int main(void) {
    int * ptr = (int*)0x12345678;
    printf("%d", *ptr);
    return 0;
}

I got a segmentation fault. But why? Because the virtual address 0x12345678 is not yet allocated? So why it is not allocated on the fly? But even if it is not allocated, there should be some bits at the address, and I can just print the 4 bytes beginning at the address 0x12345678 as an integer?

undur_gongor
  • 15,657
  • 5
  • 63
  • 75
Gab是好人
  • 1,976
  • 1
  • 25
  • 39
  • How do you know which type of data is stored at that specified address and whether the specified address is a valid address or not? – haccks Mar 01 '16 at 11:29
  • Please look at this page, https://en.wikipedia.org/wiki/C_dynamic_memory_allocation – ahmedsafan86 Mar 01 '16 at 11:30
  • 1
    @haccks No matter what is stored there, I interprete the four bytes it as an integer(using an int& pointer). – Gab是好人 Mar 01 '16 at 11:32
  • Arbitrary numbers don't all correspond to actual memory locations. Look up *MMU*. – M.M Mar 01 '16 at 11:33
  • You should specify the system which you are asking about, since the behaviour is implentation specific. On freestanding environment the code could actually be valid, where as in typical hosted environments it's usually not. – user694733 Mar 01 '16 at 11:36

3 Answers3

2

You are trying to read memory outside your process' valid address range. The operating system (not the C runtime) prevents this.

mfro
  • 3,286
  • 1
  • 19
  • 28
1

I got a segmentation fault. But why?

Address 0x12345678 doesn't belong to current process which is accessing it.

I suggest to read What is a segmentation fault?

Community
  • 1
  • 1
Jeyaram
  • 9,158
  • 7
  • 41
  • 63
1

Modern operating systems do not allow a program to access random memory wherever they want. That would be a major security hole. Any program attempting to dereference a pointer to memory unassociated with the process will exhibit implementation-defined behavior on modern operating systems, unless said program is a bootloader, kernel, etc. that can perform such operations.

You may store addresses to unassociated memory (i.e. not allocated, not memory-mapped) in pointers, but doing so is quite unsafe since dereferencing the pointer could fail.

owacoder
  • 4,815
  • 20
  • 47
  • 1
    That's not exactly true. Accessing memory through pointers is always defined. It might fail, however. A `mmap()` system call, for example, does not allocate any memory, nevertheless it's perfectly valid to access the returned address. – mfro Mar 01 '16 at 11:41
  • Nitpick: the behavior is implementation defined, not undefined. – fuz Mar 01 '16 at 11:46