LabWindows/CVI

cancel
Showing results for 
Search instead for 
Did you mean: 

How to dynamically allocate memory for a structure with an unknown number of elements?

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!

Programming Data Acquisition and Control in Measurement Studio and Labwindows/CVI
0 Kudos
Message 1 of 4
(1,946 Views)

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;
}
}

 

 

0 Kudos
Message 2 of 4
(1,915 Views)

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.

Programming Data Acquisition and Control in Measurement Studio and Labwindows/CVI
0 Kudos
Message 3 of 4
(1,899 Views)

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.  

0 Kudos
Message 4 of 4
(1,891 Views)