-3

Let we declare a pointer

int *ptr;
ptr=malloc (10 *sizeof (int));
free (ptr);

The question is how free() will free memory. Let int be of 4 bytes and the memory will be 40 bytes for int. The compiler will understand to remove first memory location provided by malloc but how it will clear another 9 int data that is other 36 bytes?

ForceBru
  • 43,482
  • 10
  • 63
  • 98
  • 8
    Check this http://stackoverflow.com/questions/1119134/how-do-malloc-and-free-work – Sumit Trehan Jan 01 '16 at 13:27
  • `malloc` is C, `new` is C++ - so why tag this C++? – Ed Heal Jan 01 '16 at 13:29
  • Because in C++ by typecast ptr=(int*)malloc (10 *sizeof (int)); it will work Therefor tagged it in C++ also. – Kartik Sethi Jan 01 '16 at 13:30
  • memory allocation, acquired by a call to `malloc()` (and family of functions) is an entry in a data structure kept in the heap. When a pointer to allocated memory is passed to `free()`, the actual address is prefixed in the heap with certain 'header data' that your program should never directly access. the `free()` function uses that header information to link that whole allocated memory data block back into the 'available' memory in the heap. So, only the one call to `free()` is necessary, as malloc and free have no concept of an array of int, as indicated in the posted code, – user3629249 Jan 01 '16 at 13:32
  • 1
    Using `malloc` in C++, even for such simple things as an array of integers, is a bad habit. Try to get used to using `new` and `new[]` if you program in C++. – Some programmer dude Jan 01 '16 at 13:32

1 Answers1

3

malloc leaves notes that free reads. In particular, it leaves a note that says how many bytes were allocated.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165