This topic is now archived and is closed to further replies.


implementing pwd

Recommended Posts

Ok this shouldn''t be too hard to do, heres the code i''ve written so far. I don''t have a linux machine handy to check it. Can someone have a look thru it and say if theres any obvious mistakes i''ve made?
#include <stdio.h>

#include <unistd.h>

#include <stdlib.h>

#include <sys/types.h>

char *pwd(){
   size_t size = 100;
      char *pwdbuf = (char*) xmalloc(size);
      if(getcwd(pwdbuf,size) == pwdbuf)
          return pwdbuf;
      if(errno != ERANGE)
         return 0;
      size *=2;

int main(void){

   char *result; // *result[] maybe???

   result = pwd();
   printf("%s\n", result); // for loop in here perhaps???

   return EXIT_SUCCESS;


Share this post

Link to post
Share on other sites
It all looks fine, except for the small issue that it''s hopelessly broken.

Ok, so maybe that''s an exaggeration. But your memory will never get freed when getcwd works. So whoever calls pwd will need to remember to call free on the result. Which you aren''t doing. Probably the best method is to use a static array and return a pointer to that, but then you can''t use the function in a multithreaded environment without extra work. You may as well make that buffer large, and forget about all the looping and size-doubling stuff. (There is probably a global variable telling you the maximum path length anyway - use that.)

[ MSVC Fixes | STL | SDL | Game AI | Sockets | C++ Faq Lite | Boost ]

Share this post

Link to post
Share on other sites