G
George Marshall
Hi all, my question is what should I do with a pointer
to be used inside a function ?
The following function should take a pointer to a null
terminated array of chars, do something with it, and
write to the other pointer (*dest).
Should I check if the *dest pointer is NULL or not
before writing to it ? Should I realloc it before
I write to it ? Should I free it if != NULL and
then allocate it again ?
Thanks.
/* Example function */
int str_do_something ( const char *src, char *dest)
{
if (src == NULL)
return 0;
do_something_to_str(src);
/* What is good practice to do with the dest pointer here ?*/
/* free before malloc ? realloc ? check if != NULL ? */
dest = malloc (strlen(src));
if (dest == NULL)
return -1;
strcpy (dest,src);
return 0;
}
to be used inside a function ?
The following function should take a pointer to a null
terminated array of chars, do something with it, and
write to the other pointer (*dest).
Should I check if the *dest pointer is NULL or not
before writing to it ? Should I realloc it before
I write to it ? Should I free it if != NULL and
then allocate it again ?
Thanks.
/* Example function */
int str_do_something ( const char *src, char *dest)
{
if (src == NULL)
return 0;
do_something_to_str(src);
/* What is good practice to do with the dest pointer here ?*/
/* free before malloc ? realloc ? check if != NULL ? */
dest = malloc (strlen(src));
if (dest == NULL)
return -1;
strcpy (dest,src);
return 0;
}