1

I am using this snippet in my code to get the path of the current executable.

 char buffer[PATH_MAX];
 ssize_t count = readlink( "/proc/self/exe", buffer, PATH_MAX );

 printf("buf: %s\n", buffer);

This works fine for the most part, and I have a duplicate located in some locations in my code, so there is no problem with it for the most time.

However, today I was debugging some command of mine that failed and I stumbled across something peculiar. This was the debug output I received.

buf: /home/[CENSORED]/IOS/IOS_Project/target/ios_historyrget/history.txt

It seems the unreliability of it finally caught up to me. What I do not understand is, why there is a rget/history.txt at the end of it? I suspect it has something to do with me writing to the file before in the same executable and the close call not having finished, but that is just a wild guess. How do I get rid of it in the best case?

monamona
  • 1,195
  • 2
  • 17
  • 43
  • 2
    https://man7.org/linux/man-pages/man2/readlink.2.html - readlink() does not append a terminating null byte to buf. – Mat Mar 16 '23 at 17:09
  • Which implies it was sheer luck that by now every time I used that snippet there was a "random" `\0` at the next position of the memory? – monamona Mar 16 '23 at 17:10
  • https://stackoverflow.com/questions/5525668/how-to-implement-readlink-to-find-the-path fixed the problem of obtaining the length and getting the data correctly truncated. This question is for c++ but the C equivalent works completely analogue. I missed the note in the manual .-. Thanks @Mat – monamona Mar 16 '23 at 17:14

0 Answers0