sam_k
sam_k

Reputation: 6023

What happen if we free memory which are already free or not malloc?

When I free the malloced memory which are not allocated using malloc than valgraind tool gives me error like:

Invalid free() / delete / delete[]

Is it dangerous in embedded C programming?

In code whenever malloc fails than i cannot judge which malloced pointer i have to release.

Upvotes: 4

Views: 2735

Answers (5)

ChrisBD
ChrisBD

Reputation: 9209

You will get undefined behaviour, typically memory corruption by freeing memory that hasn't been allocated.

I don't see how you can say that you don't know which pointer result from a malloc operation has failed?

It's really quite simple.

Declare your pointers and set them to null.

Use malloc to allocate your memory. Only use malloc on pointers that are already null (to prevent memory leaks due to reassigning a pointer to a memory block to another one). If the malloc fails then the pointer will remain null.

When it comes to freeing memory allocated by a malloc operation, only perform the free operation if the pointer is not null and once freed set that pointer to null.

Upvotes: 0

Your program could crash (as everyone replied), and even worse, it could crash much latter than when you have incorrectly called malloc. So finding these kind of bugs is hard.

A possible solution, assuming you have access to all your source code and can change it (i.e. assuming that you don't use third parties libraries which you cannot alter) might be to use Boehm conservative garbage collector, by replacing every occurrence of malloc, callocetc ... with GC_MALLOC or GC_CALLOCafter having #included <gc/gc.h> (and then, you won't bother calling free anymore).

Boehm's garbage collector being conservative, it does have a small probability to leak (because it handles every word on your call stack as a possible pointer, even if that word in fact don't carry a dereferencable pointer, but e.g. an integer or a float).

And you did not explain what embedded C programming means for you. In some industries and contexts, critical embedded C code (like the one making your aircraft flying) is not even allowed to call malloc or to use dynamically allocated heap data.

Upvotes: 2

sharptooth
sharptooth

Reputation: 170479

This will lead to undefined behavior, most likely heap corruption and/or crashing your program. It's dangerous in any kind of system.

Upvotes: 4

Sergei Nikulov
Sergei Nikulov

Reputation: 5110

Yes, it is dangerous for embedded programming. It is almost always crash you software.

Upvotes: 0

Andrew
Andrew

Reputation: 7516

If you call free on memory that was not allocated with malloc, calloc or realloc, or if you call it on memory that you have already freed, you'll get undefined behaviour.

Upvotes: 1

Related Questions