Search code examples
cmemorybus-errorstrsep

Bus Error Using strsep()


I am attempting to write a series of functions that will take a file name as input (e.g. main.c) and return the file extension using strsep(). When I run the program, I get a bus error whenever the strsep function is called. Here is the code:

static char *get_extn(char **filename)
{
        char *delim = ".";
        strsep(filename, delim);

        return *filename;
}

void format(char *filename)
{
        char *extn = malloc(256 * sizeof(char));

        strncpy(extn, get_extn(&filename), 256);
        printf("extn: %s\n", extn);
}

The main function of this program simply calls format() with a char* containing a filename:

int main(int argc, char *argv[])
{
        char *filename = "test.c";
        format(filename);

        return 0;
}

I am unsure why this program causes a bus error when executed. Thank you in advance for any help you can provide.

Edit: added main function code


Solution

  • The memory of string literals isn't guaranteed to be writable.

    Do

    char filename[] = "test.c";
    

    to create an writable char array instead.

    On my system, this memory is protected as read only and attempts to violate this protection generate segfaults.

    Also, get_ext can simply be:

    return strsep(filename, ".");
    

    and sizeof(char) is defined to be 1 (1 byte that is -- even if that byte isn't 8 bits large (rare)).