0

Program:

#include<stdio.h>
#include<sys/types.h>
#include<malloc.h>
main()
{
    int *i1, *i2;
    printf("sbrk(0) before malloc(): %x\n", sbrk(0));
    i1 = (int *) malloc(sizeof(int));
    printf("sbrk(0) after `i1 = (int *) malloc(4)': %x\n", sbrk(0));
    i2 = (int *) malloc(sizeof(int));
    printf("sbrk(0) after `i2 = (int *) malloc(4)': %x\n", sbrk(0));
}

Output 1:

 mohanraj@ltsp63:~/Development/chap8$ strace -e sbrk ./a.out
 strace: invalid system call `sbrk'
 mohanraj@ltsp63:~/Development/chap8$ 

Output 2:

 mohanraj@ltsp63:~/Development/chap8$ strace -e brk ./a.out
 brk(0)                                  = 0x8380000
 brk(0)                                  = 0x8380000
 sbrk(0) before malloc(4): 8380000
 brk(0x83a1000)                          = 0x83a1000
 sbrk(0) after `i1 = (int *) malloc(4)': 83a1000
 sbrk(0) after `i2 = (int *) malloc(4)': 83a1000
 mohanraj@ltsp63:~/Development/chap8$

Doubts:

Malloc function allocate memory in heap using the sbrk system call. Here also the program break is changed after the calling of malloc.

But, the output shows only the brk system call. strace command throws an error as "sbrk is invalid system call". Then, how is memory
allocated using malloc?

But, after the malloc statement is called, the output shows the following line "brk(0x83a1000)". Here, why the brk value is changed and why the sbrk is not printed on the output ?

Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
mohangraj
  • 9,842
  • 19
  • 59
  • 94

1 Answers1

0

I think, the heap gets created only after the first call to malloc(). Till then we don't need heap. That's why after first malloc() call, you are seeing a call to "brk(0x83a1000)".

  • I am also thinking on the same way. But why the sbrk is not called – mohangraj Jul 07 '15 at 06:49
  • I tried the same program and command on Ubuntu 14.04. I didn't get the error: "strace: invalid system call `sbrk'" malloc() calls brk() system call and not sbrk(). And this is done on the first call to malloc. It allocates a block of memory. malloc() again calls brk() only when this block gets over or is not sufficient to fit the requested memory size. And sbrk() is like a wrapper around brk(). Hope your doubt is clarified. – Narendra Kumar Jul 07 '15 at 17:32