Search code examples
cstringc-preprocessorfreedynamic-memory-allocation

Free defined String Constants


I'm working on an encryption application which implements an algorithm I made. I have about a year of experience in C and 6 months of experience in C++, but I have 6 years of experience in Visual Basic and Gambas (and I hope I'm a fast learner). I want to make my new application as efficient as possible; that's the reason I picked up C instead of C++ (I wanted to use a kind of lower-level language).

In my program, I'm using defined String constants to deal with error messages. I know that the preprocessor replaces the macro name with the actual string in every occurrence. If I'm not mistaken, this means that it pre-allocates the string constant and returns a different pointer for every occurrence. Do I have to free all those string pointers? Actually it seems a little odd... Are their pointers like automatic variables (which means that they are freed upon exit from scope) or do they stay forever as constants?

I use a dedicated header file called messages.h, which contains the definitions of every possible error message the program may use, so that I can change the Language etc. more easily; thus I can't write them as string constants directly. I thought of declaring them as constant variables, but then I either have to use a C file with the actual values and declare the header versions as extern, or have all the constants re-declared inside every file I include the messages.h header (believe me, I have more than 20 file consisting that project, and about 50-100 messages, plus the prompt messages — about 30 long ones — so it would consume considerable memory).

What do you suggest? Should — and more importantly can I — free the pointers to constants?


Solution

  • Welcome to C, I hope you never return to VB ;), ... macros, no, you don't have to free those "strings", and it doesn't returns a different pointer for every occurrence, take a look:

    #include <stdio.h>
    
    #define ERROR_MSG "Bla bla bla"
    
    int main(void)
    {
        printf("%p\n", (void *)ERROR_MSG);
        printf("%p\n", (void *)ERROR_MSG);
        return 0;
    }
    

    Output:

    0x40061c
    0x40061c
    

    As you can see the same address is printed.