...
When memory is freed, its contents may remain intact and accessible , because it is at the memory manager's discretion when to reallocate or recycle the freed chunk. The data at the freed location may appear valid. However, this can change unexpectedly, leading to unintended program behavior. As a result, it is necessary to guarantee that memory is not written to or read from once it is freed.
...
Code Block | ||
---|---|---|
| ||
int main(int argc, const char *argv[]) { char *buff; buff = (char *)malloc(BUFSIZ); if (!buff) { /* Handle error condition */ } /* ... */ free(buff); /* ... */ strncpy(buff, argv[1], BUFSIZ-1); } |
Compliant Solution
Do In this compliant solution do not free the memory until it is no longer required.
Code Block | ||
---|---|---|
| ||
int main(int argc, const char *argv[]) { char *buff; buff = (char *)malloc(BUFSIZ); if (!buff) { /* handleHandle error condition */ } /* ... */ strncpy(buff, argv[1], BUFSIZ-1); /* ... */ free(buff); } |
...