Search code examples
csegmentation-faultgetcwd

getcwd() returns NULL after new pointer is created


I've just started learning linux and C, please don't judge me strictly.

I'm trying to find a current working directory and to open file in this directory to find a specific word. It gives correct cwd if I find only cwd, but when I added while loop cwd is null.

#include <unistd.h>
#include <stdio.h>
#include <limits.h>
main(){
char *buff;
char *currentDir =getcwd(buff,PATH_MAX);

printf("Current directory: %s\n",currentDir);

FILE *file;
char *filename = "profile";
file = fopen(filename,"r");
if(file == NULL)
{
fprintf(stderr,"File %s wasn't found\n",filename);
}

while(1)
{
    char buffer[80];
    char *token;
    fgets(buffer,80,file);
    if(feof(file))
    {break;}
    else{
    *token = strtok(buffer,"=");
        if(strcmp(token,"HOME")==1);
        {
        printf("HOME token is found");
        } 
    }
free(token);
}

fclose(file);
}

The output: Current directory: (null) Segmentation fault


Solution

  • buff is pointing to random memory.

    You might like to declare buff like so:

    char buff[PATH_MAX] = "";
    

    If on Linux then one can alternatively let getcwd() allocate the memory needed by doing so:

    char * currentDir = getcwd(NULL, 0);
    

    currentDir needs to be passed to free() when done with it, and buff is not needed then.