473,405 Members | 2,415 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,405 software developers and data experts.

How to handle pointers inside of a function ?

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;
}

Nov 13 '05 #1
7 2332

"George Marshall" <g.********@nospam.com> wrote in message
news:_r********************@twister2.libero.it...
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;
}


I usually design the function to take a garbage pointer in and initialise it
within the function.
In this case, I would use the return value of 0 for an error (either, the
src pointer is garbage or the memory allocation fails), and would return the
result from strcpy or perhaps the amount of memory allocated to the new
pointer if you are doing some other function.
HTH
Allan
Nov 13 '05 #2
George Marshall wrote:
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 ?
It's up to you; just make sure you document it so that users of your
function (including you next week) know how it works. For example,
users need to know that the function as implemented below allocates
memory, so that they, the users, have to free it later.
/* Example function */
int str_do_something ( const char *src, char *dest)
int str_do_something ( const char *src, char **dest)

Since you are modifying dest, you need to pass in a pointer to it. Or
you could have the function return a char *.
{
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));
*dest = malloc (strlen(src) + 1);

Don't forget the terminating NULL.
if (dest == NULL)
if (*dest == NULL)
return -1;
strcpy (dest,src);
strcpy (*dest,src);
return 0;
}


It also might be better to do_something to the new string, not the
original. It is generally best to have a function do one thing
(return modified copy of string) rather than two (modify string,
return copy of modified string).

char *str_do_something ( const char *src )
{
char *dest = NULL;
if ( src ) {
if ( (*dest = malloc (strlen(src) + 1)) ) {
strcpy(*dest, src);
do_something_to_str(dest);
}
}
return dest;
}

Nov 13 '05 #3

"Allan Bruce" <al*****@TAKEAWAYf2s.com> wrote in message
news:bm**********@news.freedom2surf.net...

"George Marshall" <g.********@nospam.com> wrote in message
news:_r********************@twister2.libero.it...
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;
}

I usually design the function to take a garbage pointer in and initialise

it within the function.
In this case, I would use the return value of 0 for an error (either, the
src pointer is garbage or the memory allocation fails), and would return the result from strcpy or perhaps the amount of memory allocated to the new
pointer if you are doing some other function.
HTH
Allan


Since I was bored, I have written a sample program that I would use for
doing what you wish. Ignore it, use it or rape it, up to you ;-)


#include "stdlib.h"
#include "stdio.h"
#include "string.h"

int strSomething(const char *xiSrc, char **xoDst);

int main (void)
{
char *src = "Some Text Here";
char *dst = NULL;
int memAllocd;

if ((memAllocd = strSomething(src, &dst)) == 0)
printf("Error Allocating Memory\n");
else
printf("Memory Allocated: %d Bytes\nContents: %s\n", memAllocd, dst);

/* Free the memory allocated */
if (dst)
free(dst);

return 0;
}

/************************************************
* Name: strSomething
* Desription: xxx
************************************************/
int strSomething(const char *xiSrc, char **xoDst)
{
/* I use xiXXX for pointers that are valid coming into a function
and should not be altered. xoXXX for pointers which are garbage
and should be allocated and alterd. */
int lMemAllocd;

if (xiSrc == NULL)
return 0;

/* Allocate enough memory for the string and NULL terminator */
if ((*xoDst = malloc(lMemAllocd = strlen(xiSrc)+1)) == NULL)
return 0;

/* Do something to the string */
strcpy(*xoDst, xiSrc);

return lMemAllocd;
}
Nov 13 '05 #4
George Marshall <g.********@nospam.com> wrote:
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 ?
If you are writing to memory through a pointer you should /always/ check
it's != NULL (unless you already know for sure it's a valid pointer).
Should I realloc it before
I write to it ? Should I free it if != NULL and
then allocate it again ?
If you do so in the example you provide below, the result of both
strategies is nothing more but a memory leak, as the caller of the
function will never be able to retrieve the new pointer.

Additionally, (re)allocation will only be possible if dest is not
declared as an array.
Thanks.

/* Example function */
int str_do_something ( const char *src, char *dest)
{
if (src == NULL)
return 0;

do_something_to_str(src);
Ouch. You _do_something_to_a_const_char_*_ here, which is presumably not
what the caller of this function expects to happen.
/* What is good practice to do with the dest pointer here ?*/
/* free before malloc ? realloc ? check if != NULL ? */
dest = malloc (strlen(src));
Severe error if dest was an array originally!
if (dest == NULL)
return -1;
strcpy (dest,src);
Booom (read: undefined behaviour)!
You did not allocate enough memory to hold the copy of src.
return 0;
}


How do you expect anybody to access the memory dest currently points to,
once you lost the only reference to it after your function returned?

Common practice is to let the caller take care of the memory allocation,
check for NULL pointers, eventually let the caller supply an additional
size argument (like in strncpy), and return a pointer to the resulting
string, like in the following (admittedly silly) example:

/*--------------8<----------------------------*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *do_something_to( char *s )
{
char *p;

for ( p = s; *p; p++ )
if ( *p == 'u' )
*p = 'x';

return s;
}

char *str_do_something( char *dest, const char *src )
{
if ( dest == NULL || src == NULL )
return NULL;

strcpy( dest, src );

return do_something_to( dest );
}

int main( void )
{
char s[10] = "useless";
char t[10];

if ( str_do_something( t, s ) == NULL )
return EXIT_FAILURE;

printf( "s: %s\nt: %s\n", s, t );
return EXIT_SUCCESS;
}

/*--------------8<----------------------------*/

Another possibility is to take only src as argument, allocate dest in
the function and return it to the caller, much like the (non-standard)
strdup function available on many implementations.

HTH

Regards
--
Irrwahn
(ir*******@freenet.de)
Nov 13 '05 #5


George Marshall wrote:
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 ?
Just document the interface as requiring *dest to be NULL and test for
that. Keep it simple. Assuming you want to keep *dest as a parameter,
I'd write your function as:

int str_do_something ( const char *src, char **dest)
{
int ret = 0;
if (dest == NULL) {
ret = -1;
} else if (*dest != NULL) {
ret = -2;
} else if (src != NULL) {
*dest = malloc (strlen(src) + 1);
if (*dest == NULL) {
ret = -3;
} else {
(void)strcpy (*dest,src);
do_something_to_str(*dest);
}
}
return ret;
}

Regards,

Ed.
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;
}


Nov 13 '05 #6
On Mon, 13 Oct 2003 08:34:02 GMT, George Marshall
<g.********@nospam.com> wrote:
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;
}


Unless you need to distinguish the reason for failure, i'd make
the function return a pointer instead:

char *str_do_something (const char *src)
{
char *dest = NULL;

if (src)
{
do_something_to_str (src);

dest = malloc (strlen (src));
if (dest)
strcpy (dest,src);
}

return dest;
}

Nick.

Nov 13 '05 #7
George Marshall wrote:
Hi all, my question is what should I do with a pointer
to be used inside a function ?


[ snip ] ...

Thank you all. All right.
Nov 13 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
by: Howard | last post by:
Hi, I recently had a problem where I decided to store objects in a vector. (Previously, I had always stored pointers in vectors). Well, naturally, when storing an object in a vector, using...
388
by: maniac | last post by:
Hey guys, I'm new here, just a simple question. I'm learning to Program in C, and I was recommended a book called, "Mastering C Pointers", just asking if any of you have read it, and if it's...
13
by: Bonj | last post by:
Specifically, is there any difference between usin void MyFunction(const HANDLE myhandle an void MyFunction(const HANDLE& myhandleref ?? is the latter likely to cause problems (such as I...
7
by: Ioannis Vranos | last post by:
I have been checking C++/CLI lately by using VC++ 2005 Express Beta 1 (should be called Alpha though). In managed extensions we could pass managed pointers to functions taking unmanaged pointers...
7
by: Eli Luong | last post by:
Hi, Sorry if I accidentally posted a blank post before. But, I was wondering, I'm practicing with pointers right now, and wanted to know if I am using it correctly in the following code. By...
5
by: Dinesh Kumar | last post by:
Hi all I am using VB.NET for a Connector dll in Delphi client and some webservice . can you tell me how to handle pointers in Vb.net which are passed by delphi client as parameters in function...
2
by: Gary Wessle | last post by:
Hi I need help organizing this program in the right way. I included the code below which compiles and runs and gives the desired effect to a certain point, but I don't know what the next step...
2
weaknessforcats
by: weaknessforcats | last post by:
Handle Classes Handle classes, also called Envelope or Cheshire Cat classes, are part of the Bridge design pattern. The objective of the Bridge pattern is to separate the abstraction from the...
3
by: googlinggoogler | last post by:
Hi This should all be pretty standard C stuff, but I'm going to use terms like mouse callback to communicate what Im tyring to do. Basically I have my program whirling around in an infinite...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.