Quantcast
Viewing all articles
Browse latest Browse all 22009

Getting directory of executable failed [duplicate]

This question already has an answer here:

So I've used the following code a couple of times and always put it directly into the main function, which always worked flawlessly. But today I tried to pack it into a separate function. This is the function I wrote:

char *getexedir(char *pth)
{
    char path_save[512];
    char *p;
    char *exe_dir = malloc(512);
    if(exe_dir == NULL) {
        printf("Failed to allocate memory.\n");
        return(NULL);
    }

    if(!(p = strrchr(pth, '/'))) {
        if(getcwd(exe_dir, sizeof(exe_dir)) == NULL) {
            perror("Failed to get current cwd");
            return(NULL);
        }
    }
    else {
        *p = '\0';

        if(getcwd(path_save, sizeof(path_save)) == NULL) {
            perror("Failed to get current cwd");
            return(NULL);
        }

        if(chdir(pth) < 0) {
            perror("Failed to change directory");
            return(NULL);
        }

        if(getcwd(exe_dir, sizeof(exe_dir)) == NULL) {
            perror("Failed to get changed cwd");
            return(NULL);
        }

        if(chdir(path_save) < 0) {
            perror("Failed to change to previous directory");
            return(NULL);
        }
    }

    return(exe_dir);
}

Executing this code always failes at the second getcwd() with the error message "Numerical result out of range". Can somebody please explain the reason for that?

I am using Ubuntu 18.04, gcc (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0


Viewing all articles
Browse latest Browse all 22009

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>