0

I'm coding some program and at one point of my code, I'm browsing a directory. In order to make a string concording to the path and file name, I have this code:

char *aux;
aux = (char *) malloc(strlen(directory) + strlen(files[j] + 1));

sprintf(aux, "%s/%s", directory, files[j]);

//Debugging...
char b[100]; sprintf(b, "Path + file: %s\n", aux); write(1, b, strlen(b));
char c[100]; sprintf(c, "File: %s\n", files[j]); write(1, c, strlen(c));

When I execute my program, the output I get is:

Path + file: ./Path/file.txt!
File: file.txt

As you can see, in first output string, file has an extra character (!) that doesn't belong to the path nor the file (as you can see in the second output string). I also tried adjusting the malloc size to different values and this still happens. Why?

user157629
  • 624
  • 4
  • 17
  • 4
    Carefully count your required characters, and remember, you need one for the terminator in addition to both strings *and* that separating `'/'` . Now, how big was that malloc? You're program invokes *undefined behavior*. – WhozCraig Jan 03 '21 at 18:31
  • PLease edit the question and show a [mcve]. too many details missing. – OldProgrammer Jan 03 '21 at 18:31
  • You do not need to cast` malloc` - see [casting malloc bad](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – Ed Heal Jan 03 '21 at 18:40
  • 1
    You need to have space for the EOS char but you're doing it the wrong way. Also, you need space for the `/` you're adding. You want: `aux = malloc(strlen(directory) + strlen(files[j]) + 1 + 1);` – Craig Estey Jan 03 '21 at 18:43
  • 1
    Indeed, that was it... – user157629 Jan 03 '21 at 18:47
  • Manually counting the number of characters is bound to lead to errors. That is why GNU libc has `asprintf`, it automatically allocates the correct amount for you. For systems without GNU libc look [here](https://stackoverflow.com/questions/40159892/using-asprintf-on-windows) for how to implement it yourself. – koder Jan 04 '21 at 13:28

0 Answers0