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;
}
In your code, by saying
word = str1;
malloc()-ed pointerLater , 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,
malloc() and family in C..int main() should be int main(void) at least, to conform to the standard.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With