Search code examples
c++charconstantsallegro5

Memory management w/ const char * and al_get_native_file_dialog_path()


I'm using a library function which returns a const char * variable. Below is the code:

if (something) {
     const char* file = get_filename();
     save(file);
}

Is there any need to deallocate the file variable inside the block, since it's in a block?

The function I'm using is al_get_native_file_dialog_path(), from allegro 5 library.

I've tried to search for any documentation on how the const char * variable is allocated, but nothing..


Solution

  • Is there any need to deallocate the file variable inside the block, since it's in a block?

    A (const) pointer inside a scoped block is still just a pointer.

    There are no special actions taken (e.g. to automatically deallocate the memory it points to), when the scope is left.

    So we can't actually tell unless knowing how that pointer was allocated by

    const char* file = get_filename();
    

    It could be something like

    const char* get_filename() {
        static const char* hardcoded_stuff = "TheFileName.txt";
        return hardcoded_stuff;
    }
    

    or

    const char* get_filename() {
        const char* filename = new char[MAXFILENAME];
        // ... determine and initialize filename ...
        return filename;
    }
    

    The first version doesn't require memory deallocation from the client side, while the second one does.


    I'm using a library function ...

    Indicates you are using some code that isn't under your control. So you have to attend the documentation of that library, or ask the authors.


    I've tried to search for any documentation on how the const char * variable is allocated, but nothing..

    Well, did you check their example in the documentation?

    I didn't spot any code to deallocate the pointer obtained with al_get_native_file_dialog_path().