Ladder

Malloc

malloc returns a pointer to the start of a region of memory on the heap. It takes in the number of bytes to allocate.

Knowing the differences between mallocing data on the heap and declaring data on the stack is important for CS162.

Consider the commented out code char copied[length + 1]

  • If we were to use this line of code instead of the line with malloc, what would happen?

  • It's possible we get a segfault or the returned string is garbage!

    • This happens because we declared our string on the stack inside the str_copier function frame and returned a pointer to the string located in the function frame

    • But when we return from str_copier, the stack frame is deallocated so now we have a dangling pointer to a location in the deallocated function frame!

    • So never declare things on the stack and then return them!

So why don't we always malloc everything?

  • The nice thing about the stack is that anything we declare on the stack will automatically be deallocated for us when we leave the function.

  • However, when we malloc memory, we must remember to free the memory ourselves or we might run out of memory!

  • So after we are done using the malloced memory, we should have a call to free

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]) {
    // Declare a string
    char *str = "Help";
    printf("Copied str: %s\n", str_copier(str));
    // What's missing here? free(str);
    return 0;
}

// Returns a malloced copy of the string
char *str_copier(char *str) {
    int length = strlen(str);

    char *copied = malloc(sizeof(char) * (length + 1));
    // Consider the following commented out code
    // char copied[length + 1];

    strcpy(copied, str);
    return copied;
}

Output:
Copied str: Help
// Or segfault or garbage if the stack declaration is used