I have a function in which I make use of a local array. I would like to return a pointer to this, but of course one cannot do this unless one manually allocates memory. Therefore I would like to know if allocation like so:
for(i = 0; i < 26; i++)
{
llist[i] = malloc(sizeof(SomeStruct));
}
can be later freed like so:
// (where ptr is a pointer to the first allocation in llist)
for(i = 0; i < 26, i++)
{
free(ptr);
ptr += sizeof(SomeStruct);
}
Edit:
Seems I can’t do this. Is there any way in which I could free all the memory given only a pointer to the first element? Or should I take a different approach entirely?
No, it cannot. There is no guarantee that these blocks are allocated consecutively. In fact, they are almost certainly not with all the modern implementations I’ve seen. Most store the size of the block and often other information immediately before each block. Also, if your memory is fragmented, the blocks might wind up anywhere in the free space between other data, where there is not sufficient room to place them consecutively.