-2

I'm currently doing the Exploit-Exercises on level02 where in script I see a function called 'asprintf',asprintf(&buffer, "/bin/echo %s is cool" , getenv("USER")); buffer = null; before this function call.

Please explain to me in plain english what this function do and why it is there, I know that there is another post asking the same thing but it didn't help me that much. (and YES I read the man page!)

Please no ignore or question delete, it's not the 1st time, (message to the moderators).

DELETE_ME
  • 11
  • 1
  • 3

2 Answers2

1

I think the asprintf function you mention is a variant of sprintf that is specific to the glibc standard library. The first argument to the function is not a pointer to a character array, as with sprintf, but a pointer to char * variable that will hold the address of a newly-allocated char array. That is, the asprintf function does the same as sprintf but, rather than working with a fixed size char array, it allocates space for the string that it builds. The array allocated by asprintf has to be freed, at some later point, by the caller.

Kevin Boone
  • 4,092
  • 1
  • 11
  • 15
  • No, `asprintf` is also POSIX, and [musl-libc](http://musl-libc.org/) has it so it is not specific to `glibc` – Basile Starynkevitch Nov 03 '17 at 09:56
  • 2
    The Linux documentation for `asprintf` says, and I quote, "These functions are GNU extensions, not in C or POSIX." With gcc, it is necessary to define __GNU_SOURCE to get its prototype. – Kevin Boone Nov 03 '17 at 09:58
  • Sorry, it is in some TS extension [Dynamic memory extensions](http://en.cppreference.com/w/c/experimental/dynamic) of the C standard. But it is no more Glibc specific, even if it used to be. [musl-libc](http://musl-libc.org/) has it. And the Linux documentation mentions some *BSD having it also – Basile Starynkevitch Nov 03 '17 at 09:59
1

Apparenty you are looking for a sample usage of asprintf:

char *buffer = NULL;
if (asprintf(&buffer, "The counter is %d\n", 42) < 0) 
  { perror("asprintf failed"); exit(EXIT_FAILURE); };

// now buffer points to a heap allocated string "The counter is 42\n".

printf("%s", buffer);   // print the string on the terminal

free(buffer);           // free the buffer allocated by `asprintf`.
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115