Keyboard shortcuts

Press โ† or โ†’ to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Solution

Note

Clicking the button below automatically creates a blood oath with the course. It only works if you actually tried to do the exercise beforehand. Click at your own risk.

Reveal the solution.

Using the debugger you probably noticed that the words array contains the same word multiple times, or complete garbage (depending on where you placed your break point). If you looked even more closely, you may noticed that it contains the same pointer pointing to the same address multiple times.

The root cause is the input function. Letโ€™s see why. Here is a stripped down version of the exercise program, focusing on the problem. Click on the buttons below to simulate this programโ€™s stack line by line.

#include <stdio.h>
#include <stdlib.h>

char* input(void) {
    char word[4] = {0, 0, 0, 0}; // 4 bytes, stack allocated.
    fgets(word, 4, stdin);
    return word; // Return an address to the stack!
}

int main(void) {
    int i = 0; // 4 bytes, stack allocated.
    char* words[2] = {NULL, NULL}; // 8 bytes, stack allocated (assuming 32-bits pointers).
    for (i = 0; i < 2; i++) {
        words[i] = input();
        printf("words[%d] == %s\n", i, words[i]);
    }
    return 0;
}
๐Ÿญฏ Address  Data
โ”‚ ffffe000 ???????? <main's return address>
โ”‚ ffffdffc ???????? <main's stored ebp>
โ”‚ ffffdff8 ????????
โ”‚ ffffdff4 ????????
โ”‚ ffffdff0 ????????
โ”‚ ffffdfec ????????
โ”‚ ffffdfe8 ????????
โ”‚ ffffdfe4 ??
โ”‚ ffffdfe3 ??
โ”‚ ffffdfe2 ??
โ”‚ ffffdfd1 ??

As we can see above, inputโ€™s issue is that it returns data from its stack, data which gets overwritten right away when another function is called. So, what do you think the fix would be?

Tip

Click here to get a first hint.

Donโ€™t use the stack, use the heap. How would you allocate memory on the heap?

Click here to get a second hint.

malloc. malloc is the solution. Donโ€™t forget its friend, free.