(supersedes <mn***********************@YOURBRAnoos.fr>)
Frodo Baggins wrote on 21/09/05 :
I would like to know if this code snippet effectively allocates and
deallocates mem for the 2-D arr
char** retStrArr(void)
{
char** arr;
int i=0;
arr = (char**) malloc(NUM_OF_STRINGS*sizeof(char*));
for(i=0;i<NUM_OF_STRINGS;i++)
{
arr[i]=(char*) malloc(STR_LENGTH*sizeof(char));
/* strcpy(arr[i],"abc"); */
}
return arr;
}
int main(void)
{
int i=0
char** arr=retStrArr();
for(i=0;i<NUM_OF_STRINGS;i++)
{
free(arr[i]);
}
free(arr);
}
My compiler just told me that there is something wrong with your code :
main.c:8: warning: no previous prototype for 'retStrArr'
main.c: In function `retStrArr':
main.c:11: error: implicit declaration of function `malloc'
main.c:11: warning: nested extern declaration of `malloc'
<internal>:0: warning: redundant redeclaration of 'malloc'
main.c:11: error: `NUM_OF_STRINGS' undeclared (first use in this
function)
main.c:11: error: (Each undeclared identifier is reported only once
main.c:11: error: for each function it appears in.)
main.c:14: error: `STR_LENGTH' undeclared (first use in this function)
main.c: In function `main_':
main.c:23: error: syntax error before "char"
main.c:24: error: `NUM_OF_STRINGS' undeclared (first use in this
function)
main.c:26: error: implicit declaration of function `free'
main.c:26: warning: nested extern declaration of `free'
main.c:26: error: `arr' undeclared (first use in this function)
main.c:28: warning: nested extern declaration of `free'
main.c:26: warning: redundant redeclaration of 'free'
main.c:26: warning: previous implicit declaration of 'free' was here
Please provide a compiling code if you want an evaluation...
Once fixed, and secured, the code is fine :
#include <stdlib.h>
#define NUM_OF_STRINGS 4
#define STR_LENGTH 32
static char **retStrArr (void)
{
char **arr = malloc (NUM_OF_STRINGS * sizeof *arr);
if (arr != NULL)
{
int i = 0;
for (i = 0; i < NUM_OF_STRINGS; i++)
{
arr[i] = malloc (STR_LENGTH * sizeof *arr[i]);
sprintf (arr[i], "abc%d", i);
}
}
return arr;
}
int main (void)
{
char **arr = retStrArr ();
if (arr != NULL)
{
int i = 0;
for (i = 0; i < NUM_OF_STRINGS; i++)
{
printf ("%s\n", arr[i]);
free (arr[i]);
}
free (arr);
}
return 0;
}
--
Emmanuel
The C-FAQ:
http://www.eskimo.com/~scs/C-faq/faq.html
The C-library:
http://www.dinkumware.com/refxc.html
"There are 10 types of people in the world today;
those that understand binary, and those that dont."