Pergunta

First, I declare variables before the main() function:

// Files
FILE *density_model_file;
char *density_model_filename;
float *density_array;

Next, I open the FILE * for reading and allocate memory for the density array:

density_model_file = open4read(density_model_filename, program_name);
density_array = allocator(density_model_size, sizeof(float));

Up to this point, the debugger shows everything is working fine. Here is the step that I can't seem to fix, where I am attempting to load data into the calloc'd array:

density_array = floatfromfile(sizeof(float), density_model_size, density_model_file, density_model_filename);

The density_array has a NULL value after this step for some reason. Here is the code for this function (contained in a separate .c file). I have bolded the part where I think the issue exists:

float * floatfromfile(unsigned long int entrysize, int numentries, FILE *inputfile, const char *filename)
        {
        /* Declaration of density model array size variable */
    int numbytes;

    **void *temparray = 0;
    /* Writes the gravity model to file */
    numbytes = (int)fread(temparray, entrysize, numentries, inputfile);**


    /* Checks that the forward model file has a sufficient number of entries */
    if (numbytes == numentries)
        {
        printf("loaded %i values from %s using fread()\n", numbytes, filename);
        return((float *)temparray);
        }
    else
        {
        printf("ERROR: %i data points read from %s of %i needed\n", numbytes, filename, numentries);
        return((float *)temparray);
        }
    }

Any insight would be much appreciated. I think the issue might be that calloc() returns a pointer to a void array. I can provide the other functions if needed.

Foi útil?

Solução 2

fread expects to be able to write its results into an allocated memory block. But you're giving it temparray which has not been allocated—in fact its value is 0. So you're giving fread the address 0 to write into, which is likely to cause the program to crash. Instead you need to pass your allocated pointer density_array at this point.

Outras dicas

You seem to have a misunderstanding about how pointers work. What you need to do is pass density_array into floatfromfile as an argument.

What you are doing instead is overwriting the pointer to your allocated memory, with the return value from floatfromfile. That return value is always NULL because that's what you assigned it to (as temparray).

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top