Question

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
Was it helpful?

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) ...

OTHER TIPS

sizeof(buf) will return the size of char* which will be however many bits wide your processor is (32 bits or 64 bits).

What you want is to use the magic number you malloc'ed with, in this case 1024.

Try this:

#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, 1024)) != NULL)
            printf("pwd : %s\n", cwd);
    else
            perror("getcwd() error : ");
    return 0;
}

char *getcwd(char *buf, size_t size);
Here you are giving the size as sizeof(buf) which will return the size of the buf pointer which will be machine dependent.
You have to specify 1024 in the argument to getcwd.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top