简体   繁体   中英

General question regarding allocating memory for an integer in C

I am currently learning about dynamic memory allocation in C and am having difficulty with a particular concept. For using malloc for a particular integer, I need to put a previously declared integer within that space.

The following below is what I am putting in as my code.

void example(int ab)
{
int* intPtr=(int*)malloc(sizeof(int));
*intPtr = &ab;
}

I am not trying to run a program or anything. I just want to see if I have the right idea about some basic memory allocation.

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 ie address of local variable , in that case you are loosing dynamic memory as nothing is pointing to previously allocated dynamic address.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM