Reputation: 48
I am implementing a function that reads a line in C from stdin. Here is the code:
char * stdin_getline(){
unsigned buffer_size = 100;
char *string = malloc(buffer_size);
char *string_temp;
char temp;
int i=0;
while(1) {
scanf("%c", &temp);
if (temp == '\n') {break;}
if (i == buffer_size-1) {
*(string+buffer_size) = '\0';
string_temp = malloc(buffer_size);
strcpy(string_temp, string);
free(string);
buffer_size *= 2;
string = malloc(buffer_size);
strcpy(string, string_temp);
free(string_temp);
}
*(string+i) = temp;
i++;
}
*(string+i+1) = '\0';
return string;
}
int main() {
char *temp_line;
temp_line = stdin_getline();
printf("%s\n", temp_line);
free(temp_line); // Is this line needed?
return 0;
}
Do I really need to free the temp_line pointer inside the main function?
Upvotes: 0
Views: 145
Reputation: 5486
The function call is irrelevant to the question. Everything that was allocated by malloc
must be deallocated using free
in order to avoid memory leaks.
Upvotes: 2