Hi, I got a problem with memory allocation (that's my assumption) in my prog...
My program purpose is to read from file and put it inside the struct array TRecord.
this is the file format:
Code:
915 200 | buy supplies for morning tea
1030 15 | rob the bank
1045 60 | pay the programmer
1115 100 | phone new client
This is my struct:
Code:
struct tasks
{
int in_time; /*contain the 1st int eg: 915 from line 1*/
int complete_time; /*contain the 2nd int eg: 200 from line 1*/
char *description; /*the description without "|" */
} TRecord;
I ve sucessfully insert all the stuff inside my array, in which I proved with printing the array, HOWEVER this only work when I print from inside my function "insert_task" below, IF I try to print from main(), it give me segmentation fault (which 99% memory allocation problem). This is my main & function:
Code:
main (argc......,argv....)
{
FILE *fp;
int i;
TRecord *trec;
workerfile = open_file( argv[0], argv[1], "r" );
insert_task( trec, workerfile );
/* i = 1;
while( trec[i] != NULL )
{
printf( "%d\n", trec[i].in_time );
printf( "%d\n", trec[i].complete_time );
printf( "%s\n", trec[i].description );
i++;
}
*/ /* this is the loop which cause the error*/
return 0;
}
void insert_task( TRecord *trec, FILE *fp )
{
char *string;
char *taskdescp;
char buffer[BUFFSIZE];
char *tokenized;
int array_subscript, i, len;
array_subscript = 1;
i = 1;
fgets( buffer, BUFFSIZE, fp );
len = strlen( buffer );
string = ( char* ) malloc( ( len + 1 ) * sizeof( char ) );
strcpy( &string[i], buffer );
while( ......)
{
....
....
....
printf( "%d\n", trec[array_subscript].in_time );
printf( "%d\n", trec[array_subscript].complete_time );
printf( "%s\n", trec[array_subscript].description );
array_subscript++;
i++;
fgets( buffer, BUFFSIZE, fp );
len = strlen( buffer );
string = ( char* ) malloc( ( len + 1 ) * sizeof( char ) );
strcpy( &string[i], buffer );
}
/* you see a few line above that printf from inside the functions work fine, all printed out perfectly */
return;
}
Anyone has the solution?
I believe someone will give me this solution which is changing:
TRecord *trec; into TRecord trec[ASIZE];
I dont want to do this since it's not allowed in the proj spec...
thanks for the time to read my code,
Ferdinand