Question

For a little Arduino-Fun-project using WaveHC, I would like to store the filenames on the SD-card in a 2-dimensional char-array.

Don't have enough C-knowledge though.

I tried:

...
FatReader root;
FatVolume vol;
dir_t dirBuf;
char **allFilenames;
...

//get number of files
int fileCount = 0;

while(root.readDir(dirBuf) > 0) {

    fileCount++;
}

//prepare array, filenames will always be 8 + 1 
allFilenames = malloc(fileCount * sizeof(char[9]));

Now if fileCount gets bigger then say 15, it seems to overflow heavily when assigning filenames and trying to access them.

So my questions are 1. is the malloc()-statement correct? 2. if yes, my method will not work because of memory-limitations, correct?

Thank you

Was it helpful?

Solution

Your malloc is incorrect. fileCount * sizeof(char[9]) is equal to fileCount * 9, which is not a size you want to use for a double char pointer. Your double char pointer should point to a segment of data which is a multiple of sizeof(char*), not a multiple of 9.

Try something like:

allFilenames = malloc(fileCount * sizeof(char*));
for(int i = 0; i < fileCount; i++) {
    allFilenames[i] = malloc(9);
}

EDIT: The main problem is that you only allocate memory to the double pointer. Since the double pointer points to other pointers, you need to allocate memory for those pointers as well.

You could also declare your allFilenames variable as a pointer to array instead, in which case you will only need one malloc since you only use one pointer. Like this:

char (*allFilenames)[9];

If you do this your malloc is correct as it is, though you could change sizeof(char[9]) to 9 since they are always equal.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top