Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: clean up your widgets!

...

Code Block
bgColor#FFCCCC
langc
#include <stdlib.h>
 
struct gadget {
  int i;
  double d;
  char *p;
};
 
struct widget {
  char *q;
  int j;
  double e;
};
 
void func(void) {
  struct gadget *gp;
  struct widget *wp;
 
  gp = (struct gadget *)malloc(sizeof(struct gadget));
  if (!gp) {
    /* Handle error */
  }
  /* ... Initialize gadget ... */
  wp = (struct widget *)realloc(gp, sizeof(struct widget));
  if (!wp) {
    free(gp);
    /* Handle error */
  }
  if (wp->j == 12) {
    /* ... */
  }
  /* ... */
  free(wp);
}

Compliant Solution

This compliant solution reuses the memory from the gadget object but reinitializes the memory to a consistent state before reading from it:

Code Block
bgColor#ccccff
langc
#include <stdlib.h>
#include <string.h>
 
struct gadget {
  int i;
  double d;
  char *p;
};
 
struct widget {
  char *q;
  int j;
  double e;
};
 
void func(void) {
  struct gadget *gp;
  struct widget *wp;
 
  gp = (struct gadget *)malloc(sizeof (struct gadget));
  if (!gp) {
    /* Handle error */
  }
  /* ... */
  wp = (struct widget *)realloc(gp, sizeof(struct widget));
  if (!wp) {
    free(gp);
    /* Handle error */
  }
  memset(wp, 0, sizeof(struct widget));
  /* ... Initialize widget ... */

  if (wp->j == 12) {
    /* ... */
  }
  /* ... */
  free(wp);
}

Noncompliant Code Example

...