-4

Look at the code:

#include<stdio.h>


 #include<stdlib.h>
void main()
{
  int *p;
  p = malloc(6);
  p = realloc(p, 10);
  if (p == NULL)
  {
    printf("error");
   exit(1);
   }
}

Take this example for the code, suppose the total memory is 10 bytes and 2 bytes is used by the declaration of pointer to type int and ohter 6 bytes by malloc function the remaining 2 bytes is occupied by other programs, now when i run realloc function to extend the memory that pointer is pointing to, it will search for 10 bytes in memory and when it is not available it allocates 10 bytes of memory from heap area and copies contents of malloc and paste it in new allocated memory area in heap area and then delete the memory stored in malloc right?

Does realloc() return a NULL pointer because the memory is not available? No right!? It does go to heap area for the memory allocation right? It does not return a NULL pointer right?

john
  • 53
  • 1
  • 6

2 Answers2

3

Correct -- if realloc can't resize the memory block you pass in, it makes a new one, copies the data, and deallocates the old one.

HOWEVER:

  1. malloc implementations do not typically operate on a byte granularity. Most of the ones I've seen round everything up to the nearest 16 bytes, since it makes accounting easier, and many users will need that alignment anyway. In your case, this would end up making the realloc a no-op, since both sizes round up to 16 bytes.

  2. In most common multitasking operating systems, the only memory accessible to your application is its own -- other applications' memory will never get in your way. Memory allocated by libraries or other threads might, though.

  • Yeah ok, take a look at this If realloc cant allocate 10 bytes cos the rest of the 2 bytes is occupied by other programs will it return a NULL Pointer? – john Aug 25 '12 at 06:32
  • The other two bytes *cannot* be occupied by "other programs"; they have their own heap to work with. –  Aug 25 '12 at 06:43
  • @john What you are thinking about is called fragmentation. It is possible that `realloc` fails to grow an existing chunk in place. In this case it grabs a new chunk from the heap, copies the old contents, and returns the new pointer. But you are assuming that consecutive calls to `malloc` will return contiguous memory. This is not generally the case, as duskwuff is pointing out. For example, malloced memory will have a certain alignment. It is also common to have multiple pools (or arenas) for chunks with sizes in different ranges, and use `mmap` for very large requests. – Greg Inozemtsev Aug 25 '12 at 07:20
1

As stated at the specification for realloc:

If the new size of the memory object would require movement of the object, the space for the previous instantiation of the object is freed.

nneonneo
  • 171,345
  • 36
  • 312
  • 383