0

I already have XXX struct and getXXX() function. Now i need function to access yyy field of XXX struct.

typedef struct _XXX_ {
    //--other data
    char yyy[MAX_YYY_LEN];
} XXX;

XXX *getXXX(void);

const char* myFoo(void){
    XXX *ptrToXXX;
    ptrToXXX = getXXX();
    return ptrToXXX->yyy;
}

I have two questions: Will data returned by myFoo() be accessible after function termination, or it may point to nowhere, cause out of scope? Do i need to destruct ptrToXXX ? I mean, if i call myFoo() 1000000 times - will it allocate a lot of memory for XXX * pointers?

Thank you.

Denis Golovkin
  • 106
  • 2
  • 11
  • What's the implementation of `XXX *getXXX(void);`? – πάντα ῥεῖ Jul 08 '16 at 02:33
  • Implementation of `getXXX()` is unknown (i have only header and lib), but it will return pointer to one and only one object, that exists for sure and will exist "forever". – Denis Golovkin Jul 08 '16 at 02:38
  • Well, memory for the pointer will be allocated on the stack every time you call that function. The object will stay the same if there's only one object (e.g. a `static` declared inside `getXXX()`). – πάντα ῥεῖ Jul 08 '16 at 02:42
  • I'm sorry to pester, but memory, that allocated on the stack every time i call that function - is it need to be deallocated? – Denis Golovkin Jul 08 '16 at 02:45
  • No, the stack is balanced automatically. – πάντα ῥεῖ Jul 08 '16 at 02:47
  • As long as the XXX object ptrToXXX is pointing to is guaranteed to be valid by the getXXX() implementation - as you commented already - (and yyy being public...), everything is fine with your function. ptrToXXX is nothing more than a variable on the stack, which is cleaned up automatically, as Panta Rei said already. Counter-example: Imagine getXXX() would return a new object (`new XXX()`) every time you call it. ptrToXXX would still be cleaned up, but not the XXX object it pointed to --> memory leak! If you then `delete ptrToXXX;` before returning, you return a pointer to invalid memory... – Aconcagua Jul 08 '16 at 03:28

0 Answers0