...
Non-Compliant Code Example
Wiki Markup |
---|
This example from Kerrighan & Ritchie \[[Kerrighan 88|AA. C References#Kerrighan 88]\] shows items being deleted from a linked list. Because {{p}} is freed before the {{p->next}} is executed, {{p->next}} reads memory that has already been freed. |
Code Block |
---|
|
for(p = head; p != NULL; p = p->next) {
free(p);
}
|
...
To correct this error, a reference to p->next
is stored in q
before freeing p
.
Code Block |
---|
|
for (p = head; p != NULL; p = q) {
q = p->next;
free(p);
}
|
...
In this example, buff
is written to after it has been freed. These vulnerabilities can be relatively easily exploited to run arbitrary code with the permissions of the vulnerable process and are seldom this obvious. Typically, allocations and frees are far removed making it difficult to recognize and diagnose these problems.
Code Block |
---|
|
int main(int argc, char *argv[]) {
char *buff;
buff = (char *)malloc(BUFSIZE);
if (!buff) {
/* handle error condition */
}
...
free(buff);
...
strncpy(buff, argv[1], BUFSIZE-1);
}
|
...
Do not free the memory until it is no longer required.
Code Block |
---|
|
int main(int argc, char *argv[]) {
char *buff;
buff = (char *) malloc(BUFSIZE);
if (!buff) {
/* handle error condition */
}
...
strncpy(buff, argv[1], BUFSIZE-1);
...
free(buff);
}
|
...