I'm supporting some c code on Solaris, and I've seen something weird at least I think it is:
char new_login[64];
...
strcpy(new_login, (char *)login);
...
free(new_login);
My understanding is that since the variable is a local array the memory comes from the stack and does not need to be freed, and moreover since no malloc/calloc/realloc was used the behaviour is undefined.
This is a real-time system so I think it is a waste of cycles. Am I missing something obvious?
IN MOST CASES, you can only free() something allocated on the heap. See http://www.opengroup.org/onlinepubs/009695399/functions/free.html .
HOWEVER: One way to go about doing what you'd like to be doing is to scope temporary variables allocated on the stack. like so:
{
char new_login[64];
... /* No later-used variables should be allocated on the stack here */
strcpy(new_login, (char *)login);
}
...
You can only free() something you got from malloc(),calloc() or realloc() function. freeing something on the stack yields undefined behaviour, you're lucky this doesn't cause your program to crash, or worse.
Consider that a serious bug, and delete that line asap.
The free() is definitely a bug.
However, it's possible there's another bug here:
strcpy(new_login, (char *)login);
new_login[sizeof(new_login)-1]='\0';
strncpy(new_login, (char *)login, sizeof(new_login)-1 );
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