Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

asprintf() usage

Status
Not open for further replies.

keshavp

Programmer
Apr 12, 2001
1
IN
Hi, can someone please help me in understanding the argument 'char **ret' in the prototype of asprintf() function?
It is written in the man pages that "asprintf() return a pointer to a buffer sufficiently large to hold the string in the 'ret' argument".
I have a declaration in my program
char **buf;

it gives me a bus error when i run the program.
Will someone Please help me?
regards,
keshav

 
You're probably not initializing buf properly before passing it to asprintf().

For your purposes, you most likely don't need to declare buf as a double pointer. Try something like this:

char *buf;
const char foo[]="hello";

asprintf(&buf,"!!%s!!",foo);

if (buf!=NULL) {
/* asprintf() succeeded and buf points to "!!hello!!" */

/* Sometime later ... */
free(buf);
}

By passing the address of buf, you give asprintf() the actual pointer rather than just a copy of it (C has no pass by reference), which is what asprintf() needs.

If you really want to use a double pointer for some reason, you'll have to initialize and pass it like this:

char **buf;
const char foo[]="hello";

buf=malloc(sizeof *buf); /* Allocate space for 1 pointer to char */

if (buf!=NULL) {
asprintf(buf,"!!%s!!",foo);
if (*buf!=NULL) {
/* asprintf() succeeded and *buf points to "!!hello!!" */

/* Sometime later ... */
free(*buf);
}
free(buf);
}

This is a silly way to do it, obviously the 1st example using a single pointer is more sensible for this sort of thing.

It should be pointed out that asprintf() isn't part of C -- it's a compiler-specific extension that's not available on all C implementations (for those that might try using it and wonder why their compiler says that it doesn't exist).

Russ
bobbitts@hotmail.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top