Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Playing with pointer incrementation in C [closed]

Tags:

c

I started playing a bit around in c when i found out that you can increment pointers.. So i thought, why not try to see if it's possible to clear my RAM with this program:

#include <stdio.h>

int main()
{
    int number = 0;
    int *pointer = &number;
    while (true) {
        pointer++;
        *pointer = 0;
    }
    return 0;
}

Is the reason why this doesn't work my operating system, or does the C language have exceptions for this?

Thanks in advance!

like image 904
Reppien Avatar asked Jul 01 '26 07:07

Reppien


2 Answers

Is the reason why this doesn't work my operating system, or does the C language have exceptions for this?

It is undefined behavior as far as the language is concerned. It is up to the OS to decide what happens when you muck with memory you don't own.

You allocated sizeof int bytes for number, store its address in a pointer, and then continue to walk past that block of memory until something obvious goes wrong. As soon as you increment pointer and write to that location you invoke undefined behavior.

You cannot just read and write to random memory locations as you please (well, you can, your program just isn't guaranteed to behave in any certain way).

like image 122
Ed S. Avatar answered Jul 03 '26 03:07

Ed S.


In any modern operating system, every process has its own address space. In it, it will find its own executable code and data. Therefore, you cannot simply access "the RAM of your computer". All you can do is mess things up in the address space of your program.

You can easily see this by running the following code in parallel:

int main()
{
    int i=0;
    printf("The address of i = %p\n",&i);
    sleep(60);
}

You will (probably) see that all processes print out the same memory address. Of course, they are not pointing to the same physical bits of memory.

(ps. when shared libraries ("DLL") are loaded, you will have processes all pointing to the same physical bits in memory. That way, a lot of executable code has to be loaded only once for all processes. This will be read-only memory, so no process can alter executable code of other processes using the same library. The mechanism behind it is called memory mapping, have a look at the mmap() system call for more info.)

like image 37
mvds Avatar answered Jul 03 '26 03:07

mvds



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!