J.Fernandes J.Fernandes - 20 days ago 5
C Question

Store getcwd on a struct on a function

typedef struct
{
char Path[100];
} DirectoryInformation;

void Getskelutofdirectorie(char * dir, int lvl)
{
DirectoryInformation DI[100];
char cwd[1024];

//Search recursive

// where I want to put the path on the struct to use on main

getcwd(cwd, sizeof(cwd));
strcpy(DI[0].Path, cwd);
}

int main(void)
{
DirecoryInformation DI[100];
printf("%s", DI[0].Path);

}


I can print the path but if i use on main function will work.

Can somebody help me out?

It executes without error but when I print out make segmentation fault

Answer

Your code invokes undefined behavior by using value of variable DI having automatic storage duration and not initialized, which is indeterminate.

Call the function with passing pointer to the struct to store the data, then store there.

typedef struct
{
  char Path[100];
} DirectoryInformation;

void Getskelutofdirectorie(DirectoryInformation * DI, char * dir, int lvl)
{
    char cwd[100]; // cwd was too long, so there was risk of buffer overrun when copying

    //Search recursive

    //where i want to put the path on the struct to use on main

    getcwd(cwd, sizeof(cwd));
    strcpy(DI[0].Path, cwd);
}

int main(void) 
{
    DirectoryInformation DI[100] = {{""}}; // initialize for in case the function fails to set values
    Getskelutofdirectorie(DI, NULL, 0); // pass proper parameter
    printf("%s", DI[0].Path);

}
Comments