1

What part of this quote from the getcwd man-page am I misunderstanding?

   char *getcwd(char *buf, size_t size);
   ...
   As  an  extension  to  the  POSIX.1-2001 standard, Linux (libc4, libc5,
   glibc) getcwd() allocates the buffer dynamically using malloc(3) if buf
   is NULL.  In this case, the allocated buffer has the length size unless
   size is zero, when buf is allocated as big as  necessary.   The  caller
   should free(3) the returned buffer.

because

 21         char * buffer = NULL;
 22         size_t bufferSize = 0;
 23         getcwd(buffer, bufferSize);
 24         printf("%s\n", buffer);

is causing a Seg-Fault at line 24 and gdb's backtrace tells me buffer = 0x0?

EDIT:

 getcwd(buffer, bufferSize);

still doesn't work for whatever reason, but

 buffer = getcwd(NULL, 0);

does

Jens
  • 69,818
  • 15
  • 125
  • 179
Kdawg
  • 167
  • 11

2 Answers2

1

You miss that C has only call by value; not call by reference:

getcwd(buffer, bufferSize);

can NOT change the pointer buffer (only what buffer points to, but since it is NULL...). That's why you need to use the value returned by (this non-standard version of) getcwd.

You also missed to read the RETURN VALUE section of that man page or misinterpreted the quoted part where it says The caller should free(3) the returned buffer. :-)

Jens
  • 69,818
  • 15
  • 125
  • 179
  • AAAAAAAAAAAAAAAAAHHHHHHHHHHHHHHHHH, yes you are correct, this is why getline and getdelim take char **buffer... – Kdawg Oct 10 '14 at 11:03
  • @Kdawg Exactly. If you think this answer was helpful, the next step would be to klick the up-arrow and/or the check mark below to "accept" the answer. – Jens Oct 10 '14 at 12:56
  • sorry my man, "Vote Up requires 15 reputation"... one day I'll get there – Kdawg Oct 10 '14 at 13:43
0

It should be:

 printf("%s\n", buffer);

since %s takes a char*, not a char.

You would know this if you had warnings on.

o11c
  • 15,265
  • 4
  • 50
  • 75