In addition to my earlier question Dynamically allocating an array in a function in C , which was answered and works fine, It doesn't seem to work if one of my structure fields are pointers themselves.
Here is what I am trying to do now:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct myData {
unsigned char* dataBuffer;
int lengthInBytes;
}myData;
// suppose this is dynamic. it return a value according to some parameter;
int howManyDataBuffers() {
// for this demo assume 5.
return 5;
}
// this just fills data for testing (the buffer is set with its length as content. exp:3,3,3 or 5,5,5,5,5)
int fillData(int length, myData* buffer) {
buffer->dataBuffer = (unsigned char*)malloc(length);
memset(buffer->dataBuffer,length,length);
buffer->lengthInBytes = length;
return 1;
}
int createAnArrayOfData(myData** outArray,int* totalBuffers) {
// how many data buffers?
int neededDataBuffers = howManyDataBuffers();
// create an array of pointers
*outArray =(myData*)malloc(neededDataBuffers * sizeof(myData));
// fill the buffers with some data for testing
for (int k=0;k<neededDataBuffers;k++) {
fillData(k*10,outArray[k]);
}
// tell the caller the size of the array
*totalBuffers = neededDataBuffers;
return 1;
}
int main(int argc, const char * argv[]) {
printf("Program Started\n");
myData* arrayOfBuffers;
int totalBuffers;
createAnArrayOfData(&arrayOfBuffers,&totalBuffers);
for (int j=0;j<totalBuffers;j++) {
printf("buffer #%d has length of %d\n",j,arrayOfBuffers[j].lengthInBytes);
}
printf("Program Ended\n");
return 0;
}
The result is BAD_ACCESS in this line :
buffer->dataBuffer = (unsigned char*)malloc(length);
I'll appreciate any help with finding what am I doing wrong.
Thanks.