07-08-2019 03:43 PM - edited 07-08-2019 03:45 PM
I need to open a file and read in X number of analog input channels that my program will log. I have gotten by in the past with the following allocation:
static struct DAQChannel *DAQAIChannels[100]; DAQAIChannels[numAIChannels] = (struct DAQChannel*) malloc(sizeof(struct DAQChannel));
The trouble with this is that, if I don't allocate memory for all 100 channels, I get an error when I try to free all of the memory like this because some of the memory hasn't been allocated:
free(DAQAIChannels);
How should I use pointers such that I can allocate and free memory dynamically for an unknown number of AI channels? I should be a little more clear that, as I read line by line from the file, I create a new index in the structure array so the number of channels is not known until the last AI channel line is read.
Thank you!
07-09-2019 03:05 AM
Does it really work, if you allocate all 100 channels ?
I think your problem is that
free(DAQAIChannels);
tries to free DAQAIChannels (the the array of 100 struct DAQChannel pointers) , which wasn't allocated by malloc().
Instead you might want to do something like :
... // initializing the array with NULL for (i=0; i< 100,i++) DAQAIChannels[i] = NULL; ... // Allocate a channel DAQAIChannels[a_channel]= malloc(sizeof(struct DAQAIChannel));
// Add errorhandling ... // free all used channels for (i=0; i< 100,i++) {
if (DAQAIChannels[i] != NULL) {
free(DAQAIChannels[i]);
DAQAIChannels[i] = NULL;
}
}
07-09-2019 03:00 PM
This appears to have worked, though I'm sure there is some other way that I could declare a pointer and then increment the pointer to allocate the next object in the structure.
07-10-2019 01:48 AM
That would be something like this
static struct DAQChannel **DAQAIChannels ... //Allocate the array DAQAIChannels=malloc ( NUMBER_OF_CHANNELS* sizeof(*DAQChannel)) ... // basically same code as above ... // free array free (DAQAIChannels);
Then you are able to resize the array using realloc().
Another option would be not to use an array of pointers to struct DAQChannel but to use an array of struct DAQChannel.
Then you don't need to allocate memory for every used channel.