0

Take a function that creates a char* and does something with it.

void print_hello_twice()
{
    char* hello = "hello";
    printf(hello);
    printf(hello);
}

This is a silly pointles example, but I wanted to avoid anything extraneous to my question, which is this:

I've read that when you assign a string literal to char* variable:

The actual string literal "hello" is stored in the read only memory section. The variable "word" though, is just a pointer created in the stack that as a value, holds the address of the first element of the string.

Memory allocation when using struct to defined a user defined type

So, does this mean that this is a potential source of a memory leak? What happens to the piece of memory containing "hello" itself (not the pointer to it) once print_hello_twice returns? Is it freed up in some way?

2

Yes and no. Yes it is stored to memory, but the way in which it is declared has no memory leaks (try making a test file and running valgrind to see for yourself).

What does cause a memory leak is when you allocate memory for a variable using malloc (or similar) and don't subsequently free that memory. For example:

void print_hello_twice()
{
    char* hello = malloc(6);
    hello = "hello";
    printf(hello);
    printf(hello);

    // you must free alloc'ed memory when finished
    free(hello);
}

Now doing it this way in such a small program seems a little unnecessary, but for much larger and more complex programs it is, in fact, essential.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .