I'm having a problem with my array of structs and segmentation faults. I have this struct that represents one line of a source file:
This is the code that tries to fill the array of structs, which is a global variable called program:
When I try:
I get:
This results in a segmentation fault later on in my code which I'm sure is from me trying to access some null data. Any ideas?
Code:
struct threeTokens {
int lineNumber;
char* cmd;
char* param;
}; line;
Code:
program = malloc(numLines * sizeof(line));
while(NULL != fgets(buffer, SIZE, fp)){
tokenPtr = strtok(buffer," ,\n");
while(NULL != tokenPtr){
switch(count){
case 0: program[curLine].lineNumber = atoi(tokenPtr);
paramIndex += strlen(tokenPtr);
break;
case 1: program[curLine].cmd = (char*)malloc(strlen(tokenPtr) * sizeof(char));
strcpy(program[curLine].cmd, tokenPtr);
paramIndex += strlen(tokenPtr);
break;
default: paramLength += strlen(tokenPtr); break;
}
program[curLine].param = (char*)malloc(paramLength * sizeof(char));
for(i = 0; i < paramLength; i++){
program[curLine].param[i] = buffer[paramIndex + i];
}
tokenPtr = strtok(NULL, " \n");
}
curLine++;
}/*End While of buffer*/
Code:
for(i = 0; i < numLines; i++){
printf("%d\t%s\t%s\n",program[i].lineNumber, program[i].cmd, program[i].param);
}
Code:
0 (null) 0 (null) 0 (null) 0 (null) 0 (null)
Comment