This program create structures of the type "pf_space" and allocates memory as they're created. The problem is, it doesn't work like the book. malloc never returns false and therefore you can continue making structures until the program crashes. On my PC, I tracked down the offending line. After creating 1034 pf_spaces, the program will crash on the line "pf_spaces = p;". Since it compiles fine I have no idea what the problem could be. The fact that it's not crashing until the pointer is assigned is even more confusing. I now bow out to all your superior c programming experience. Thank you.


#include <stdlib.h>

struct pf_space {
  int id;
  char *label;
} SPACE, *pf_spaces[0];

int pf_total_spaces = 0;

int pf_create_space (int id, char *label) {
  struct pf_space *p;
  if ((p = malloc(sizeof(struct pf_space))) == NULL) {
    puts("Out of memory\n");
    return 0;
  }
  int i = pf_total_spaces;
  pf_spaces[i] = p;
  pf_spaces[i]->id = id;
  pf_spaces[i]->label = label;
  pf_total_spaces++;
  return 1;
}

int main (void) {
  // create spaces
  int id = 1, max = 100;
  while (pf_create_space(id, "another space") == 1 && id < max) {
    id++;
  }
  // print spaces
  int i;
  printf("pf_total_spaces = %d\n", pf_total_spaces);
  for (i = 0;i < pf_total_spaces;i++) {
    printf("space%d (id = %d, label = %s)\n", i, pf_spaces[i]->id, pf_spaces[i]->label);
  }
  return 0;
}

Here's what I get in GDB:

Program received signal SIGSEGV, Segmentation fault.
0x003dbf08 in ?? ()

Sorry to bother ya'll but I found the problem. I was able to get the program working by adding a MAX number of structures. I thought C handle a variable length pointer array, but I guess you have to tell it everything. Maybe this will help someone else facing the same problem:

#define MAX_SPACES 1024

struct pf_space {
  int id;
  char *label;
} SPACE, *pf_spaces[MAX_SPACES];

Thanks for replying Salem, I must have been writing my reply as you were. Yes, I mistakenly thought C would somehow allocate more space for my spaces.

This article has been dead for over six months. Start a new discussion instead.