Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to use free() to understand how it works

Tags:

To understand the usage of free in the C programming language I tried running this code on Ubuntu, but on running the EXE file I am receiving a SIGABRT error. Why is the program not exiting normally?

#include<stdio.h> #include<stdlib.h>  int main() {    int ret;    int *ptr;    ptr = (int *)malloc(sizeof(int)*10);    free(ptr);    ptr = &ret;    free(ptr);    return 0; } 
like image 225
user3314983 Avatar asked Apr 14 '14 05:04

user3314983


People also ask

What is free () used for?

The free() function in C++ deallocates a block of memory previously allocated using calloc, malloc or realloc functions, making it available for further allocations. The free() function does not change the value of the pointer, that is it still points to the same memory location.

What does free () do in C?

The free() function in C library allows you to release or deallocate the memory blocks which are previously allocated by calloc(), malloc() or realloc() functions. It frees up the memory blocks and returns the memory to heap. It helps freeing the memory in your program which will be available for later use.

How does free () know how many bytes to free?

How does free() know the size of memory to be deallocated? The free() function is used to deallocate memory while it is allocated using malloc(), calloc() and realloc(). The syntax of the free is simple. We simply use free with the pointer.


1 Answers

Attempting to free a pointer you didn't get from malloc (or one of its friends) causes undefined behaviour. Your second free(ptr) call attempts just that.

From the C spec, §7.22.3.3 The free function, paragraph 2:

The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.

like image 94
Carl Norum Avatar answered Nov 09 '22 23:11

Carl Norum