Kamie Xeng
Kamie Xeng

Reputation: 37

Trigger the invocations of system call in Linux, C program?

When the below C program is run in a Linux,the execution of which line must trigger invocation of system call, why? What is invocation of system call ?

void main()
{
    double x=1;
    double y;
    double *z;

    z=(double *)malloc(sizeof(double)); // line 1
    scanf("%f", &y);                    // line 2
    *z=sqrt(y);                         // line 3
    y=y*2.0;                            // line 4
    printf("y=%f, *z=%f\n", y, *z);     // line 5
    y=y/x;                              // line 6 
    printf("y=%f",y);                   // line 7
}

Upvotes: 0

Views: 713

Answers (2)

Thomas Schar
Thomas Schar

Reputation: 1751

The confusion above for people is syscall vs libc. Not every malloc will require a syscall - in fact, most shouldn't.

The Heap: LibC needs to manage the memory allocated to the heap(s). This is the area from which all of your individual malloc() allocations are sourced. When the heap is exhausted libc will invoke syscalls to kernel space to request more memory / reallocate / release pages / etc.

Malloc: LibC provides the user level code to assign memory blocks within the heap. It handles all the individual manner in which it allocates and frees this memory. If the allocation can't be done within the existing heap capacity it will trigger the Heap syscall.

If you look at the libc malloc code you'll see how this works between __libc_malloc() and _int_malloc(). In _int_malloc() it will fallback to sysmalloc() which will then perform a kernel memory heap change.

Upvotes: 0

gmoshkin
gmoshkin

Reputation: 1135

A call to malloc invokes a system call because the operating system manages the memory.

Calls to scanf and printf invoke system calls because the operating system manages i/o operations.

Invocation of a system call is a call for an operating system service.

Upvotes: 3

Related Questions