-1

I want to concatenate "/bin/" and "touch" so that I will have "/bin/touch".

In my program, I have

        char* filePath = malloc((strlen("/bin/") + strlen(rv[0]))* sizeof(char));
        filePath = strcat("/bin/",rv[0])

First of all, rv[0] contains a string, "touch". I allocate 10 bytes in memory by using malloc function, and filePath will be the pointer to those 10 bytes of memory. Because, the total length of the string concatenated ("/bin/touch") will be 10.

The program executes normally until the second line which gives me a segmentation fault. Did I make any mistake on the strcat function?

  • You're *appending* to a string literal. `strcat` does not work like that. You'd *strcpy* to `filePath` and then *strcat* – Antti Haapala -- Слава Україні Nov 11 '18 at 10:04
  • 1
    Also you're not allocating space for the null terminator (+ 1), and `sizeof(char)` is 1 by definition. – Antti Haapala -- Слава Україні Nov 11 '18 at 10:05
  • When copying strings, `strcat()` copies the input string up to and including the zero terminator. Your `malloc()` size does not allow for the presence of that zero terminator, so is one character shorter than needed. `strcat()` therefore writes past the allocated end of `filePath` - which gives undefined behaviour. A call of `strcat()` should not even compile when given two string literals. If it is, then either your code is forcing it in some way you haven't shown, or your compiler/library is flawed. I'll bet on the former. – Peter Nov 11 '18 at 10:07

1 Answers1

0

Take a look at the reference for how to use strcat:

char *strcat( char *dest, const char *src );

Appends a copy of the null-terminated byte string pointed to by src to the end of the null-terminated byte string pointed to by dest.

The first parameter must thus be a pointer to a memory location large enough to hold the bytes of both the C string already there and the C string pointed to by src.

You call strcat("/bin/",rv[0]) and thus try to write into memory where the string literal "/bin/" is stored .. which is normally in readonly memory, thus You get a segmentation fault.

You need to copy "/bin/" first into the allocated memory pointed to by filePath and then append rv[0] there.

Daniel Jour
  • 15,896
  • 2
  • 36
  • 63