Is it correct to return a memory address in function?

6

I was asked to design a function that was called, open a .txt file and return the pointer of this file, that is, return a memory address. However, as far as I know the memory is only temporarily allocated to functions, ie after the execution of the function the memory is free to be used by another part of the program.

I think the most correct would be to declare the file pointer to a main function ( main ) and then send the pointer as a parameter to a function that opens the file and "points" it to the memory address that was sent. Am I right?

    
asked by anonymous 29.08.2015 / 19:30

1 answer

6

There is a misconception in your thinking, perhaps you lack a better understanding of stack and < in> heap .

If the information is in stack you really can not trust it to be there when the function is finished. But you rarely create a pointer to the stack.

But if it is allocated in heap , you can return a pointer to this allocated area with no problems. The area remains available even when the function is finished. This is the main reason to use heap .

You are even correct in your thinking from the point of view of code organization. The most correct is the function that needs an information to allocate the necessary memory for the object, to pass this to the function that will fill this object and then when to return it to release this memory.

Nothing prevents you from allocating a function that will fill and return, but becomes asymmetric because it is responsible for allocating and does not release (nor could in this case). This gives rise to errors. Well-built functions require consumers to deliver the memory that is already in the loop. Even if it needs a reallocation within it, this is less problematic.

So from the technical point of view you can do as you asked, but any good programmer would do the way you are thinking. You're correct.

    
29.08.2015 / 19:44