简体   繁体   English

关于在C中为整数分配内存的一般问题

[英]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. 我目前正在学习C语言中的动态内存分配,并且对某个特定概念有困难。 For using malloc for a particular integer, I need to put a previously declared integer within that space. 为了将malloc用于特定的整数,我需要在该空间中放置一个先前声明的整数。

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. 几乎没有问题,首先没有必要对malloc()的结果进行类型转换,因为它是由编译器隐式完成的。 Read Do I cast the result of malloc? 阅读我是否转换了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 是错误的,因为*intPtr是动态地址的值,编译器应该警告你喜欢

main.c:7:9: warning: incompatible pointer to integer conversion assigning to ' int ' from ' int * '; main.c:7:9:警告:指向整数转换的不兼容指针从' int * '分配给' int '; remove & [-Wint-conversion] 删除& [-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. 一旦完成使用,通过调用free()动态分配的内存。

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. 然后你用堆栈创建的内存覆盖动态内存,即局部变量的地址 ,在这种情况下,由于没有任何东西指向先前分配的动态地址,所以你正在丢失动态内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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