Access to a specific memory address

Viewed 4355

I'm a new C programmer, still learning the language itself.

Anyway - I'm trying to access a specific memory address.

I've written this code:

#include <stdio.h>

int main()
{
    int* p = (int*) 0x4e0f68;
    *p = 12;
    getchar();
}

When I try to access a specific memory address like that, the program crashes.

I don't know if this information is relevant, but I'm using Windows 7 and Linux Ubuntu.
(I've tried this code only on Windows 7).

Any explanations why the program crashes? How can I access a specific memory address (an address which is known at compile-time, I don't mean to dynamic memory allocation)?

Thanks.

4 Answers

What you're getting is a segfault - when you're trying to access memory you don't have permission to access. Pointers, at least for userspace, must point to some variable, object, function, etc. You can set a pointer to a variable with the & operator - int* somePtr = &variableToPointTo, or to another pointer - int* someNewPtr = somePtr. In kernel mode (ring 0) or for OS development, you can do that, BUT IT IS NOT ADVISED TO DO SO. In MS-DOS, you could destroy your machine because there was no protection against that.

Related