Pointers to deallocated memory

This applies to memory allocated on the stack and to memory dynamically allocated. The following is a poorly written function that returns a string allocated on the stack in a function:

    char *get()     {         char c[] { "hello" };        return c;    }

The preceding code allocates a buffer of six characters and then initializes it with the five characters of the string literal hello, and the NULL termination character. The problem is that once the function finishes the stack frame is torn down so that the memory can be re-used, and the pointer will point to memory that could be used by something else. This error is caused by poor programming, but it may not be as obvious as in this example. If the function uses several pointers ...

Get Beginning C++ Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.