Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a local structure variable not dynamically allocated?

Tags:

c

consider the following code:-

struct mystruct {
    int data;
    struct mystruct *next;
};

void myfunc ()
{

 struct mystruct s1;
 s1.data= 0;
 s1.next = NULL;
 myfunc2(&s1);
 ..
 ..
}

is it safe to pass the address of this local structure to other function. Will this local structure be available for use outside the function or will it be already freed ?

like image 430
Hemanth Avatar asked Feb 23 '23 20:02

Hemanth


2 Answers

It is safe to pass the address of a local variable to another function. The variable's life time extends to the end of the block (function or compound statement) in which it is declared.

It is not safe to return the address of a local variable or save a pointer to it and use it after the declaring function has returned.

like image 172
Richard Pennington Avatar answered Apr 28 '23 18:04

Richard Pennington


Your wording is awkward in the question.

You can pass it to other functions by adress. It'll still be in valid scope.

But you can't return it by adress (which you are not doing here) outside of the function in which you declared it.

like image 28
RedX Avatar answered Apr 28 '23 19:04

RedX