clinuxgetcwd

Does getcwd() ignore the size of the buffer and copy it?


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

int main() {
    
    char wd[10];

    if(getcwd(wd,BUFSIZ) == NULL){   //BUFSIZ = 8192
            perror("getcwd");
            exit(1);
    }
    printf("wd = %s\n",wd);
}

This C code works well in Ubuntu Linux 20. The size of buffer wd is 10 but if I print the wd, it can output a string that is over size 10.

I think that the function uses the pointer of wd regardless of size, so it can work well but it can also print dummy string. Is it right?

//Edit :

printf("wd2 = %s\n",wd2); -> printf("wd = %s\n",wd);


Solution

  • You lie to getcwd about buffer size.

    getcwd does not magically know the buffer size. Buffers which know their own size is not a C language feature. That's why getcwd needs the size parameter!

    So, getcwd happily writes beyond end of array.

    In C, this is Undefined Behavior. Anything can happen, and "anything" includes what you observe here.