I'm looking for the right way to allocate and deallocate chars arrays of dynamic sizes contained inside structs (an array of "Command" structs in fact). Is the following correct way to approach this problem in C? I was having many problems before I realized I had to NULL all the array entries at the start. If I don't, I get the "pointer being freed was not allocated" error.
Note that I have to free the Command struct data because I'm reusing them in a loop.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_NB_ARGS 10
typedef struct {
char* args[MAX_NB_ARGS];
} Command;
void init_commands(Command commands[2]) {
int i;
for (i=0; i<2; ++i) {
int j;
for (j=0; j<MAX_NB_ARGS; ++j) {
// If I don't null these, the free_commands
// function tries to free unallocated memory
// and breaks
commands[i].args[j] = NULL;
}
// Constant of 3 here but in reality variable size
// Idem for the size of the "args" string
for (j=0; j<3; ++j) {
commands[i].args[j] = malloc(5*sizeof(char));
strcpy(commands[i].args[j], "test");
}
}
}
void free_commands(Command commands[2]) {
int i;
for (i=0; i<2; ++i) {
int j=0;
// Do I really clear the second command?
// Debugger shows every args as nil on
// on the second iteration.
while (commands[i].args[j]) {
free(commands[i].args[j]);
commands[i].args[j] = NULL;
++j;
}
}
}
int main () {
Command commands[2];
int i=0;
// Command structs are being reused within the loop
while ((i++)<2) {
init_commands(commands);
puts(commands[1].args[2]); //test print. works.
free_commands(commands);
}
return 0;
}
structtype?while ((i++)<2) {...}is IMHO a confusing idiom: the parentheses are not needed, and the loop could just as well have been written asfor(i=1; i < 3; i++) {...}, which is much more standard (and thus:readable), IMHO.