Tarounen
Tarounen

Reputation: 1159

pointer to char changes after opendir() system call

i am currently trying to delete directories from system call using c and i am facing a weird problem. In my deleteFunction() after using the char * path to open the directory. the value of path changes

here is part of the code:

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

void deleteDir(char *path){
    //opening the directory
    printf("BEFORE %s\n",path );
    DIR *p = opendir(path);
    if (p == NULL){
        printf("Directory not Opened!\n");
        exit(2);
    }
    printf("AFTER %s\n",path );
}

void main(int argc,char *argv[]){

    if (argc != 2){
        printf("Not enough Arguments!\n");
        exit(1);
    }

    //creating the path 
    char * currentDir = getcwd(NULL,0);
    strcat(currentDir,"/");
    strcat(currentDir,argv[1]);
    //deleting the directory
    deleteDir(currentDir);
    exit(0);
}

the output produced is:

BEFORE /home/tarounen/test/newfolder
AFTER /home/tarounen/test/!�

note: i am only taking the directory name as parameter

Upvotes: 1

Views: 370

Answers (2)

molbdnilo
molbdnilo

Reputation: 66371

getcwd only allocates enough memory to hold the directory when you pass NULL.
Concatenating to its result has undefined behaviour.

If you want to use strcat, you need to provide your own buffer with enough space:

char buffer[MAXPATHLEN] = {0};
if (getcwd(buffer, sizeof(buffer)))
{
    strcat(buffer, "/");
    strcat(buffer, argv[1]);
    deleteDir(buffer);
}

Upvotes: 3

user3386109
user3386109

Reputation: 34829

The getcwd function is probably allocating just enough space to hold the current path, so adding more characters with strcat overflows the buffer, and results in undefined behavior. Try this

char path[MAXPATHLEN];
getcwd( path, MAXPATHLEN );
strcat( path, "/" );
strcat( path, argv[1] );

Upvotes: 3

Related Questions