returning pointer to a structure in C

前端 未结 4 369
情书的邮戳
情书的邮戳 2021-01-26 12:11

this program returns a pointer to a structure.
When i print the contents, the name is not being displayed properly, where as the other tw

4条回答
  •  余生分开走
    2021-01-26 12:32

    The problem here is that you're returning a pointer to a local variable. Local variables goes out of scope once the function they are defined in returns. That means that the pointer you return will point to unallocated memory after the function returns. Using that pointer will lead to undefined behavior.

    There are three ways to solve this:

    1. Use a global variable, and return a pointer to that. The lifetime of a global variable is the lifetime of the program.
    2. Use a static local variable. It also will have the lifetime equal to the program.
    3. Allocate the structure dynamically when needed, and return that pointer.

    Points 1 and 2 have a problem in that then you can only have a single object. If you modify that object, all places where you have a pointer to that single object will see those changes.

    Point 3 is the way I recommend you go. The problem with that is that once you're done with the object, you have to free the memory you allocate.

提交回复
热议问题