Search code examples
clinuxpwd

Printing Present working directory in c using pointers


Aim : Print present working directory in c on Linux machine.

Without using pointers, it is giving correct output..

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<errno.h>
int main()
{
    //char buf[1024];

    char * buf;
    char * cwd;
    buf = (char *)malloc(sizeof(char) * 1024);

    if((cwd = getcwd(buf, sizeof(buf))) != NULL)
            printf("pwd : %s\n", cwd);
    else
            perror("getcwd() error : ");
    return 0;
}

But with pointer it shows following error

getcwd() error : : Numerical result out of range

Solution

  • This is because when buf is a pointer, sizeof(buf) is the number of bytes required to store a pointer, not the size of the array, as in the code that you commented out.

    You need to pass the size that you allocated (i.e. 1024) instead, like this:

    size_t allocSize = sizeof(char) * 1024;
    buf = (char *)malloc(allocSize);
    if((cwd = getcwd(buf, allocSize)) != NULL) ...