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;
}
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?
Let's see who can provide the cleanest fix! π
Top comments (0)