1

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.

Community
  • 1
  • 1

1 Answers1

1

The problem is, you are allocating an array of structs but use it (by outArray[k]) as if it was an array of pointers. Call

fillData( k*10, &(*outArray)[k] );

instead

The difference is:

outArray[k] == *(outArray+k) that means you dereference an address at location outArray + k*sizeof(myData*) bytes. But there is no valid address stored at that location.

&(*outArray)[k] first dereferences the address stored at location outArray which is the address returned by malloc(), the start address of your array of structs. then you pass the address of the k'th structure within the array which is what you want (if you prefer, you could also write (*outArray)+k instead of &(*outArray)[k]).

Ingo Leonhardt
  • 9,435
  • 2
  • 24
  • 33