There are few issues, firstly its not necessary to typecast the result of malloc()
as it's done implicitly by compiler. Read Do I cast the result of malloc?. This
int* intPtr = malloc(sizeof(int)); /* or even malloc(sizeof(*intPtr)); is better */
is fine.
Secondly, this
*intPtr = &ab; /* *intPtr means value at allocated dynamic address, you should assign the value not address of ab*/
is wrong as *intPtr
is the value at dynamic address, compiler should have warned you like
main.c:7:9: warning: incompatible pointer to integer
conversion assigning to 'int
' from 'int *
'; remove &
[-Wint-conversion]
If you had compiled with below flags like
gcc -Wall -Wextra -Werror -Wpedantic test.c
It should be
*intPtr = ab;
Also you are not freeing the dynamically allocated memory, its leads to memory leakage. Free the dynamically allocated memory by calling free()
once usage is done.
Side note, if your intention is to do like this
intPtr = &ab; /* Before this statement intPtr was pointing dynamic memory(heap), but now that gets overwritten with stack allocated space */
then you are overwriting dynamic memory with stack created memory i.e address of local variable, in that case you are loosing dynamic memory as nothing is pointing to previously allocated dynamic address.