For your particular problem:
You allocate (*array)[i]
which is a char*
to strlen(fooString)
which is usually equivalent to sizeof(char) * strlen(fooString)
: this is error prone. You should use sizeof(*((*array)[i]))
in this case to be sure not to miss the correct type.
To free it, loop from i = 0
to i < MAX_ARRAY
and call free(array[i])
What you put in place of ...
in your code is very important.
In general, when allocating memory, be sure to respect these general ideas:
- If a functions allocates memory it frees it itself except when it is needed outside afterwards.
- If a function allocates memory needed outside afterwards, it does just this.
This allows for better code architecture and easier freeing of the memory.
For example:
First point:
void foo()
{
char *a;
a = malloc(sizeof(*a) * 5);
a[0] = 'a';
a[1] = 'b';
a[2] = 'c';
a[3] = 'd';
a[4] = 0; //or '\0' if you prefer
do_something_cool(a);
free(a);
}
The function foo
allocates memory, processes it, and frees it.
Second point:
char *halfstrdup(char *str)
{
int len;
int i;
char *newstr;
len = strlen(str);
newstr = malloc(sizeof(*newstr) * len / 2)
for (i = 0; i < len; i++)
{
if ((i % 2) == 0)
newstr[i / 2] = str[i];
}
return (newstr);
}
void foo2()
{
char *half;
half = halfstrdup("Hello, world !");
do_something_cooler(half);
free(half);
}
The function halfstrdup
just allocates and sets the memory you need and returns it, the function foo2
allocates memory through the use of halfstrdup
, then uses it and frees it.
Do not forget to free before losing track of your pointers, for example after returning from foo or foo2, you won't be able to free the allocated memory.