Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
530 views
in Technique[技术] by (71.8m points)

c - Scope of malloc used in a function

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

eg.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

You're responsible for freeing the memory you malloc.

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));

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.

You have to do either:

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

or

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...