11.04.2009

malloc vs calloc vs realloc

char* malloc(sizeOf)
Returns a pointer in the heap with the specified size. One major difference is that it does not initialize the memory.

char* calloc(numElements, sizeOfElement)
Returns a pointer in the heap with the specified size for a number of elements - usually for an array.

char* realloc(ptr, newSize)
Returns a pointer in the heap after growing or shrinking a block a memory that was allocated by using malloc, calloc or realloc.

void free(ptr)
No return value. Deallocates memory previous allocated by malloc, calloc or realloc. ptr is unchanged.

11.03.2009

Processes do not share Global Variables



In the C code above, what are the values at line 13 and 18?

At line 13, the value is 30.
At line 18, the value is 10.

Why is this you ask? It's because the fork system call produces a new child process which does not share global variables with its parent process. Each process has its own code section and the data region. The run-time stack is copied for each process, thus they are not the same variable. Threads, on the other hand, do share global variables. Great. Now you tell me.

Can you think of a way to get around this limitation?