DEV Community

Mukul Roy
Mukul Roy

Posted on

πŸš€ C Challenge: Spot the Memory Leak! 🧠

Hello Devs! Time for another round of debugging. This time, we are diving into Dynamic Memory Allocation.

Look at the code below. It’s a simple function that creates a copy of a string. But wait... there's a serious problem here.
The Code:
C

include

include

include

char* get_string_copy(char *str) {
char *copy = (char *)malloc(strlen(str) + 1);
if (copy != NULL) {
strcpy(copy, str);
}
return copy;
}

int main() {
char *my_str = "Game Changer";
char *new_str = get_string_copy(my_str);

if (new_str != NULL) {
    printf("Copy: %s\n", new_str);
}

// Is something missing here?
return 0;
Enter fullscreen mode Exit fullscreen mode

}

The Question:

Does this code have a Memory Leak? If yes, where?

How would you fix it to ensure the memory is properly managed?

What happens if we call get_string_copy inside a loop 1 million times without fixing the issue?
Enter fullscreen mode Exit fullscreen mode

Let's see who can provide the cleanest fix! πŸ”Ž

Top comments (0)