开发者

Constant pointer array with struct fields that may point to malloc allocated fields?

int main() {    
    Employee *array[SIZE]; //Employee is a typedef struct --includes char *name, DATE *dateOfBirth, DATE is also a typedef struct, has 3 int fields month, day, year,`  

fillArray(array, &count, fpin1, fpin2);

freeMemory(array, int count);

}  

fillArray(Employee *array[], int *count,  FILE *fpin1, FILE *fpin2)  
    char buffer[MAX], buffer2[MAX];  
    while (fgets(buffer, MAX, fpin1) != NULL && fgets(buffer2, MAX, fpin2) != NULL){  
        array[*count]->name = (char *) malloc(sizeof(char)*25);  
        assert(array[*count]->name != NULL);  
        strncpy(array[*count]->name, buffer, 15);  

        strncpy(buffer2, temp, 2);
        array[*count]->dateOfBirth->day = atoi(temp)
}

The code compiles but keeps failing w开发者_开发百科ith segmentation fault, it seems to fail at my fgets? or my malloc, what am I doing wrong? I really can't seem to figure that out.

Also how would you go about freeing this memory in a

freeMemory(Employee *array[], int count)

function?


Should be:

int main() {    
    Employee array[SIZE]; //Employee is a typedef struct --includes char *name, DATE *dateOfBirth, DATE is also a typedef struct, has 3 int fields month, day, year,`  

fillArray(&array, &count, fpin1, fpin2);

freeMemory(&array, int count);

}  

You aren't allocating your Employee objects anywhere, so array[0] points to some random address.


Employee* array[SIZE];

This is an array that stores pointers to Employee structs.

I think you mean

fillArray(Employee* array[], int* count,  FILE *fpin1, FILE *fpin2)
{
    char buffer[MAX], buffer2[MAX];
    int i = 0;
    while ( fgets(buffer, MAX, fpin1) != NULL && 
            fgets(buffer2, MAX, fpin2) != NULL )
    {
        // the array does not hold any valid memory address.
        array[i] = malloc( sizeof(Employee) );
        assert( array[i] != NULL );

        // now on the new employee add some char memory
        (array[i])->name = malloc( sizeof(char) * 25 );
        assert(array[i]->name != NULL);

        strncpy(array[i]->name, buffer, 15);
        strncpy(buffer2, temp, 2);

        array[i]->dateOfBirth->day = atoi(temp)

        ++i;
        (*count)++; 
    }  
}

doing array[*count] besides looking weird, always modifies the same index. You never modified *count anywhere.

This code does not check that you do not exceed the bounds of the array passed.

Also : for the freeMemory()

freeMemory(Employee* array[], int count)
{
    int i = 0;
    while( i < count )
    {
        free(array[i]);
        array[i] = NULL;
        ++i;
    }  
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜