malloc的范围在函数中使用 [英] Scope of malloc used in a function

查看:203
本文介绍了malloc的范围在函数中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当函数返回,通过的malloc分配的内存释放?还是可以仍然可以在main()函数中使用指针访问?

When a function returns, is the memory allocated via malloc freed? Or can it still be accessed in the main() function using pointers?

如:

void function(int *a)
{
    a=(int *)malloc(sizeof(int));
    *a=10;
}
int main()
{
    int *num;
    function(num);
    printf("%d",*num);
    return(0);
}

可以存储在一个整数被主)访问这里(?

Can the integer stored in a be accessed by main() here?

推荐答案

没有,使用malloc分配的内存,当你离开的范围从功能/回报。没有释放

No, the memory allocated with malloc is not freed when you leave the scope/return from the function.

您是负责释放内存的malloc你

You're responsible for freeing the memory you malloc.

在你的情况虽然,内存是在main()不入店,但那是因为你只能用一个局部变量处理。

In your case though, the memory is NOT accesible in main(), but that's because you only deal with a local variable.

void function(int *a)
{
    a=(int *)malloc(sizeof(int));

在这里, A 函数内的局部变量。指针由用C值传递的,所以 A 接收主指针的副本,当你做功能(NUM); main()中没有看到分配给指针的本地副本。

Here, a is a local variable within function . Pointers are passed by value in C, so a receives a copy of the pointer in main when you do function(num); main() does not see that you assign to that local copy of the pointer.

您所要做的不是:

void function(int **a)
{
  *a= malloc(sizeof(int));
  **a=10;
}
int main()
{
  int *num;
  function(&num);
  printf("%d",*num);
  free(num);
  return(0);
}

int* function(void)
{
  int *a= malloc(sizeof(int));
  *a=10;
  return a;
}
int main()
{
  int *num;
  num = function();
  printf("%d",*num);
  free(num);
  return(0);
}

这篇关于malloc的范围在函数中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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