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;
}