Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't free memory after char *

Tags:

c

free

I have a problem when I am trying to free memory at the end of my program. It breaks all the time. Can you tell me where is the problem please?

int main() {

char* word = NULL;
int i = 0;
char str1[12] = "oko";

while (str1[i]) {
    str1[i] = tolower(str1[i]);
    i++;
}

printf("%s", str1);

word = (char *)malloc(strlen(str1) + 1);
word = str1;
printf("%s", word);

free(word);
system("pause");

return 0;
}
like image 314
Jax-p Avatar asked Dec 02 '25 22:12

Jax-p


1 Answers

In your code, by saying

word = str1;
  1. you're overwriting the malloc()-ed pointer
  2. creating memory leak.

Later , by calling free() on word, you're invoking undefined behavior, as the pointer is no longer returned by a malloc() or family of function.

Solution: You should use strcpy() to copy the content of a string.

That said,

  1. Please see this discussion on why not to cast the return value of malloc() and family in C..
  2. int main() should be int main(void) at least, to conform to the standard.
like image 110
Sourav Ghosh Avatar answered Dec 05 '25 11:12

Sourav Ghosh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!