Jax-p
Jax-p

Reputation: 8531

Can't free memory after char *

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;
}

Upvotes: 3

Views: 1146

Answers (1)

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

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.

Upvotes: 7

Related Questions