Possible memory leak with malloc()

  • A+
Category:Languages

I have this code:

#include <malloc.h>  int main() {     int x = 1000;      //~600kb memory at this point     auto m = (void**)malloc(x * sizeof(void*));     for (int i = 0; i < x; i++)         m[i] = malloc(x * sizeof(void*));      for (int i = 0; i < x; i++)         free(m[i]);      free(m);      //~1700kb memory at this point     return 0; } 

When program starts memory consumption is about ~600kb, and when it ends ~1700kb. Is it memory leak or what?

 


malloc() acquires memory from the system using a variety of platform-specific methods. But free() does not necessarily always give memory back to the system.

One reason the behavior you're seeing might exist is that when you first call malloc() it will ask the system for a "chunk" of memory, say 1 MB as a hypothetical example. Subsequent calls will be fulfilled from that same 1 MB chunk until it is exhausted, then another chunk will be allocated.

There is little reason to immediately return all allocated memory to the system just because the application is no longer using it. Indeed, the most likely possibilities are that (a) the application requests more memory, in which case the recently freed pieces can be doled out again, or (b) the application terminates, in which case the system can efficiently clean up all its allocated memory in a single operation.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: