free() on stack memory

vidicon picture vidicon · Apr 22, 2010 · Viewed 10.4k times · Source

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?

Answer

nos picture nos · Apr 22, 2010

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.