Memory allocated without allocation using malloc, how?

The following is a simple snippet of code:

int main()
{
int *p;
p=(int*)malloc(sizeof(int));//allocate m/y 4 1 int 
printf("P=%p\tQ=%p",p,p+2);
}

In one run run, he gave me the result, as shown below:

P=0x8210008 Q=0x8210010

The starting address is P is-P = 0x8210008, the next byte is 0x8210009, the next byte is 0x821000A, the next byte is 0x821000B. So 4 bytes for int end. We did not allocate more memory using malloc. Whereas p + 2 leads us to 0x8210010, which is 8 bytes after P (0x8210008).

-1
source share
4 answers

Firstly, the fact that you typed the address does not mean that memory is allocated at this address. You simply added numbers and produced other numbers.

-, , , , , , , , C, - , ( ). , int, int x[8], x[3]. x[5], x[3]. , C , C , . C , . C ( , C ) , , C. , , . , ( , int - ), , .

-, . C , , . , . , p, int, p+0 p+1, (p+0) (p+1). p-1 p+2, . , ( ): , C: , "" , C.

, . , , , . , . 16 , 16 . b o 4096 * b + o. ( 2 20 , . , 0 4096 , 1 0.) , . ( C 65536 , .) , int p 0x0000fffc (base 0, offset 65532), int - , p+2 0x00000004, , (0x00010004).

, , . , , C, . , , . , , . , .

+4

. . p+2, , &p[2]. , , char*:

char *highWordAddr = (char*)p + 2;
+5

C , . , p+2 , , . , .

, , .

+4

Source: https://habr.com/ru/post/1681618/


All Articles