Strange pointer behavior in C

I've been experimenting with pointers. Look at this code:

#include <stdio.h>

int main() {

int numba = 1;

int *otherintptr = &numba;

printf("%d\n", otherintptr); 
printf("%d\n", *otherintptr);


printf("%d\n", otherintptr);
printf("%d\n", *otherintptr);

return 0;





Now I am well aware that (*otherintptr)++

would increase my int, but that is not my question.

After the increment, the memory location will be correctly increased by 4 bytes, which is the size of an integer.

I would like to know why the last printf command prints the memory location, while I am clearly asking to print the contents of the memory locations marked as 2358856 (I was expecting some dirty random content). Note that the second statement printf

prints the contents of memory location 2358852 (integer 1

) as expected.


source to share

4 answers

What's going on with these two lines

int numba = 1;
int *otherintptr = &numba;


due to the C compiler will generate a sequential memory layout, otherintptr

will initially point to the memory address corresponding to the variable numba

. And this refers to the stack frame allocated when called main


Now the next position on the stack (actually the previous one, considering that the stack grows on an x86-based architecture) is occupied by a variable otherintptr

. The increment otherintptr

will point to itself, so you see the same value.

To demonstrate, suppose the stack for main

starts at offset 0x20 in memory:

0x20: 0x1      #numba variable
0x24: 0x20     #otherintptr variable pointing to numa


After executing the command, the otherintptr++

memory layout will look like this:

0x20: 0x1      #numba variable
0x24: 0x24     #otherintptr variable now pointing to itself


This is why the second one printf

has the same output.



This is because the pointer value is stored at that location, just a match, print &otherprint

and see.



When you did otherintptr++

, you accidentally did otherintptr

to point to otherintptr

, that is, to yourself. otherintptr

has just been stored in memory right after yours numba


In any case, you've gotten lucky a few times here. It is illegal to use a pointer int *

to access something that is not int

and is incompatible with int

. It is not allowed to use %d

pointer values ​​for printing.



Let's say you wanted to increase the number of integers otherpointer

to ( numba

). However, you have actually increased the pointer, since it ++

binds more tightly than *

see here .

So, otherpointer

the minus variable indicates. And since there is no valid variable, dereferencing a pointer has undefined behavior. So anything can happen and you're just lucky the program didn't work. He just accidentally otherpointer

lived at this address.



All Articles