1

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

w m
  • 493
  • 1
  • 5
  • 7
  • `The main function of this program simply calls format() with a char* containing a filename.`: We don't care; we need the code. BTW, `strsep()` is bad and dangerous voodoo. You should use `strtok()` instead. – 3442 Apr 03 '16 at 22:37
  • If filename is a string literal, then you probably won't be able to write to it. That's likely the cause of the bus error. – Petr Skocik Apr 03 '16 at 22:45
  • @KemyLand added `main()` code – w m Apr 03 '16 at 22:45
  • do `char filename[] = "test.c";` instead – Petr Skocik Apr 03 '16 at 22:46

1 Answers1

1

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)).

Petr Skocik
  • 58,047
  • 6
  • 95
  • 142