Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#FFCCCC
langc
#include <stdlib.h>
 
struct node {
  struct node *next;
};
 
void func(struct node *head) {
  for (struct node *p = head; p != NULL; p = p->next) {
    free(p);
  }
}

Compliant Solution

Kernighan and Ritchie also show the correct solution. To correct this error, a reference to p->next is stored in q before freeing p.

Code Block
bgColor#ccccff
langc
#include <stdlib.h>
 
struct node {
  struct node *next;
};
 
void func(struct node *head) {
  struct node *q;
  for (struct node *p = head; p != NULL; p = q) {
    q = p->next;
    free(p);
}
head = NULL;}
}

Noncompliant Code Example

...

Code Block
bgColor#FFCCCC
langc
#include <stdlib.h>
#include <string.h>
 
enum { BUFFERSIZE = 32 };
 
int main(int argc, const char *argv[]) {
  char *buff;

  buff = (char *)malloc(BUFFERSIZE);
  if (!buff) {
     /* Handle error condition */
  }
  /* ... */
  free(buff);

  if (argc /* ... */
  > 1) {
    strncpy(buff, argv[1], BUFFERSIZE - 1);
  }
 
  return 0;
}

Compliant Solution

In this compliant solution do not free the memory until it is no longer required:

Code Block
bgColor#ccccff
langc
#include <stdlib.h>
#include <string.h>
 
enum { BUFFERSIZE = 32 };
 
int main(int argc, const char *argv[]) {
  char *buff;

  buff = (char *)malloc(BUFFERSIZE);
  if (!buff) {
     /* Handle error condition */
  }
  
  /* ... */if (argc > 1){
    strncpy(buff, argv[1], BUFFERSIZE - 1);
  /* ... */}
  free(buff);
 
  return 0;
}

Noncompliant Code Example

...

Code Block
bgColor#FFCCCC
langc
void gdClipSetAdd(gdImagePtr im,gdClipRectanglePtr rect) {
  gdClipRectanglePtr more;
  if (im->clip == 0) {
    ...
  }
  if (im->clip->count == im->clip->max) {
    more = gdRealloc (im->clip->list,(im->clip->max + 8) *
                      sizeof (gdClipRectangle));
    if (more == 0) return; //if /* If the realloc fails, then we have not lost the
       im->clip->list value. */
    if (more == 0) return; 
    im->clip->max += 8;
  }
  im->clip->list[im->clip->count] = (*rect);
  im->clip->count++;

...