Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does free result in a segmentation fault?

My code:

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

int main() { 

    int num = 0;

    printf("enter a number: ");   
    scanf("%d", &num);
    
    printf("num: %d", num);

    free(&num);

    return 0;
} 

Why can i not release (free) the memory that holds the integer entered by the user?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

According to the free(3) man page:

void free(void *ptr);
The free() function frees the memory space
pointed to by ptr, which must have been
returned by a previous call to malloc(), calloc()
or realloc(). Otherwise, or if free(ptr) has
already been called before, undefined behavior
occurs. If ptr is NULL, no operation is performed. 

If you pass free() something that has not been returned by either malloc(), calloc() or realloc() it leads to undefined behavior.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading