[C] Struct allocation crash?
(Dev-C++ in Windows Vista / GCC in Ubuntu)
My goal is to eventually read line by line from a file that contains combined lengths of text like those joined into the "input" variable.
Currently, the code below crashes the console in windows and in linux it points to a "realloc(): invalid next size" error.
I realize that most of this code is poor programming style, but I'm only looking for it to work at this point. I was wondering if there was a much more efficient way to do this code. This would probably be much easier if the number of records and the number of subnames were constant, like they are in the example "input" variable.
So I guess my questions are, what is causing the code to crash and is there a more efficient way to store an unknown number of records containing an unknown number of subnames in each record?
Please ask questions if I left out something important or need to clarify anything. Thanks!
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
int ID;
char* name;
int subs;
char** subname;
} RECORD;
int main() {
/*Sample of what would be read from a text file*/
char input[2][80] = {"1,Entry,ProcStart,ProcLoop,ProcFunc,ProcEnd,ProcStop",
"2,Phase,ProcBegin,ProcSpin,ProcHelp,ProcEnd,ProcHalt"};
RECORD* record = (RECORD*) malloc(sizeof(RECORD));;
if(record == NULL) return -1;
int records = 0;
int loop;
for(loop=0;loop<2;loop++) {
record = (RECORD*) realloc(record, sizeof(RECORD)*(records+1));
if(record == NULL) return -1;
record[records].ID = atoi(strtok(input[loop],","));
char* temp = strtok(NULL,",");
record[records].name = (char*) malloc(sizeof(char)*(strlen(temp)+1));
if(record[records].name == NULL) return -1;
strcpy(record[records].name,temp);
record[records].subs = 0;
int i;
while((temp=strtok(NULL,","))!=NULL) {
i = record[records].subs;
record[records].subname = (char**) realloc(record[records].subname,i+1);
if(record[records].subname == NULL) return -1;
record[records].subname[i] = (char*) malloc(sizeof(char)*(strlen(temp)+1));
if(record[records].subname[i] == NULL) return -1;
strcpy(record[records].subname[i],temp);
record[records].subs++;
}
records++;
}
/*Test the resulting data to see if the variables are stored correctly*/
int x,y;
for(y=0;y<2;y++) {
printf("%d:\n",y);
for(x=0;x<record[y].subs;x++) {
printf("%s\n",record[y].subname[x]);
}
}
getchar(); /*Stops the window from closing in the Windows console*/
return 0;
}