我为什么要使用免费的指针,但不是一个正常的声明? [英] Why do I have to use free on a pointer but not a normal declaration?

查看:129
本文介绍了我为什么要使用免费的指针,但不是一个正常的声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我时,我声明了一个指针,如免费使用():

 为int * TEMP =(INT *)malloc的(的sizeof(int)的)
* TEMP = 3;

而不是当我做的:

  INT TEMP = 3;


解决方案

普通声明都放在堆栈上。当函数返回堆栈指针恢复到它有函数被调用前的值,所以内存将自动收回。

根据的malloc-声明从'堆',这需要程序员来管理分配和释放分配的。

Why do I have to use free() when I declare a pointer such as:

int *temp = (int*)malloc(sizeof(int))
*temp = 3;

but not when I do:

int temp = 3;

解决方案

Normal declarations are put on the stack. When the function returns the stack pointer reverts to the value it had before the function was called, so the memory is automatically reclaimed.

Malloc-based declarations are allocated from the 'heap', which requires the programmer to manage allocations and deallocations.

这篇关于我为什么要使用免费的指针,但不是一个正常的声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆