Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I do automatic memory management in C?

In C memory allocation/deallocation done by malloc and free.

In C++ memory allocation/deallocation done by new and delete.

There are some solutions in C++ for automatic memory management like:

  • Smart Pointers.
  • RAII (Resource Acquisition Is Initialization)
  • Reference counting and cyclic references
  • ...

But how can I do automatic memory management in C?

Is there any solutions for AUTOMATIC memory management in C?

Is there any guidelines or something like that for C?

I want when I foget free a block of memory:

  • My code doesn't compile

-- or --

  • Memory automatically deallocated

And then I say: Oh, C is better than C++, Java and C#. :-)

like image 213
Amir Saniyan Avatar asked Jul 26 '11 19:07

Amir Saniyan


People also ask

Does C have automatic memory management?

Memory allocated on the heap, however, is treated differently by different languages. In C and C++, memory allocated on the heap is managed manually. In C# and Java, however, memory allocated on the heap is managed automatically.

How is memory management performed dynamically in C?

The “malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form.

What provides automatic memory management?

Automatic memory management is one of the services that the Common Language Runtime provides during Managed Execution. The Common Language Runtime's garbage collector manages the allocation and release of memory for an application.

How do you dynamically allocate a variable in C?

In C, dynamic memory is allocated from the heap using some standard library functions. The two key dynamic memory functions are malloc() and free(). The malloc() function takes a single parameter, which is the size of the requested memory area in bytes. It returns a pointer to the allocated memory.


1 Answers

You may use a Boehm garbage collector library.

like image 58
Juraj Blaho Avatar answered Oct 19 '22 13:10

Juraj Blaho