veen_99
veen_99

Reputation: 47

Getting a double free where only one free function is writtern

my code:

#include<stdio.h>
#include<stdlib.h>
#include<cs50.h>

int main(void)
{
    char *name = malloc(50 * sizeof(char));
    if(!name)
    {
        printf("Memory allocation problem.\n");
        return 1;
    }

    name = get_string("Enter your name: ");

    printf("Hello, %s\n", name);


    free(name);
}

output:

Enter your name: dog
Hello, dog
*** Error in `malloc0': double free or corruption (fasttop): 0x0000000001084050 ***

I am unable to understand where I am wrong this is a very simple code to take in name an print it but the name stored in heap memory. I am just executing free() only once but why double free error??

somebody please help me understand the problem.

Upvotes: 0

Views: 478

Answers (2)

KamilCuk
KamilCuk

Reputation: 141200

cs50 automagically manages its own memory.

Before main the libcs50 registers atexit callback in cs.50:449:

/**
 * Called automatically before execution enters main.
 */
INITIALIZER(setup)
{
    // Disable buffering for standard output
    setvbuf(stdout, NULL, _IONBF, 0);
    atexit(teardown);
}

The teardown() function deallocates all the memory allocated by libcs50:

static void teardown(void)
{
    // Free library's strings
    if (strings != NULL)
    {
        for (size_t i = 0; i < allocations; i++)
        {
            free(strings[i]);
        }
        free(strings);
    }
}

Where strings is a global object in cs50.c:67.

When you free(name) the pointer behind the name is also stored in strings[0] (assigned in get_string()).

After main() exits, the atexit registered callback are executed, and free(strings[0]) is executed which tries to double free the object.

Upvotes: 4

H.cohen
H.cohen

Reputation: 517

From the description of get_string:

Prompts user for a line of text from standard input and returns it as a string (char *), sans trailing line ending. Supports CR (\r), LF (\n), and CRLF (\r\n) as line endings. Stores string on heap,but library's destructor frees memory on program's exit. The prompt is formatted like printf(3).

so as you can see it also frees it from heap at exit.

Upvotes: 3

Related Questions