as per the discussion, your code should be *q = *(p + 1);
Enable all the warnings in your compiler. Then, in cases like q = *(p + 1)
, your compilar would have warned you regarding assignment makes pointer from integer without a cast
Here q
[p + 1
] points to a memory location which is not allocated to your program. malloc()
allocated the meemory enough to hold a single integer to p
. In other words, you are not suppossed to access memory location after malloc()
-ed memory region from your program. So, accessing [p + 1
] will result in undefined behaviour.
You can get more insight on this if you compile your program and run it through a memory debugger , say valgrind
. It will show you the memory region access violation.
EDIT:
Check the code below [line 8]
1 #include <stdio.h>
2 #include <stdlib.h>
3 int main(int argc, char const *argv[])
4 {
5 int *p = malloc(sizeof(int));
6 *p = 5;
7 int *q = p;
8 *q = *(p + 1);
9 printf("p is %p\n", p);
10 printf("q is %p\n", q);
11 return 0;
12 }
and the result [partial] after running thr' valgrind
==12786== Invalid read of size 4
==12786== at 0x80483E9: main (test71.c:8)
==12786== Address 0x402602c is 0 bytes after a block of size 4 alloc'd
==12786== at 0x4005903: malloc (vg_replace_malloc.c:195)
==12786== by 0x80483D0: main (test71.c:5)
==12786==