Search code examples
csegmentation-faultargvcoredump

Segmentation fault (core dumped) - argv - c


I am trying to open a txt file for a program entering the name of the file as a command line argument. if I provide the path as a string it works, so the problem in my code is with the command line argument. I have the following:

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

int main (int argc, char* argv[])
{
    char* filename = "/path/";
    char* name = argv[1];
    printf("%s\n", filename);
    printf("%s\n", name);
    strcat(filename, name);
    printf("%s\n", filename);
    strcat(filename, ".txt");
    printf("%s\n", filename);
    return 0;
}

I run it like so:

./program filenamewithoutextension

I get the following output when I run it:

/path/
filenamewithoutextension
Segmentation fault (core dumped)

I don't understand what is happening.


Solution

  • Note that in your code snippet filename and name are just pointers which point to read-only data, so you cannot modify the data they point to.

    You can dynamically allocate memory using malloc in order to be able to edit the data they point to. Or just allocate memory for them in stack like, filename[100] or name[100].

    Your code should be like that:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main (int argc, char* argv[])
    {
        char filename[100]; 
        char name[100];
        strcpy(filename, "/path/");
        strcpy(name, argv[1]);
        printf("%s\n", filename);
        printf("%s\n", name);
        strcat(filename, name);//You can safely modify name now 
        printf("%s\n", filename);
        strcat(filename, ".txt");//You can safely modify filename now 
        printf("%s\n", filename);
        return 0;
    }