0

I know Segmentation Fault is a general error and could be caused by different wrong memory access scenarios. I tried, but couldn't figure out what's wrong with my code.

This is the minimum reproducible example:

#include <filesystem>
#include <iostream>

using namespace std;

int main()
{
    filesystem::path filePath("file");

    if (filesystem::exists(filePath))
        cout << "file exists" << endl;
    else
        cout << "file not found" << endl;

    return 0;
}

And this is build command and execution result (the target file doesn't exist).

$ g++ -std=c++17 main.cpp
$ ls
a.out  main.cpp
$ ./a.out
file not found
Segmentation fault (core dumped)
$ g++ --version
g++ (Ubuntu 8.4.0-3ubuntu2) 8.4.0
...

Debugging shows me that the segmentation fault happens on filePath destruction point, in this part of the header (/usr/include/c++/8/bits/stl_vector.h):

      /**
       *  The dtor only erases the elements, and note that if the
       *  elements themselves are pointers, the pointed-to memory is
       *  not touched in any way.  Managing the pointer is the user's
       *  responsibility.
       */
      ~vector() _GLIBCXX_NOEXCEPT
      {
    std::_Destroy(this->_M_impl._M_start, this->_M_impl._M_finish,
              _M_get_Tp_allocator());
    _GLIBCXX_ASAN_ANNOTATE_BEFORE_DEALLOC;
      }

What's wrong in the code or the build command?

pedyram
  • 330
  • 1
  • 2
  • 11
  • 3
    g++ 8.5 doesn't compile this for me; 9.1 does - live - https://godbolt.org/z/5j4WY1h1r . I think you are right on the edge of C++17 and `` support / implementation. – Richard Critten Jul 30 '22 at 09:59
  • @RichardCritten With gcc 8 the code can be built; [you just need to link an extra lib (`-lstdc++fs`)](https://stackoverflow.com/questions/53201991/how-to-use-stdfilesystem-on-gcc-8): https://godbolt.org/z/dY6jY556f – fabian Jul 30 '22 at 10:30
  • @fabian It's not only the build. I build it, too (both with and without `stdc++fs` library flag. But I don't understand what's the reason for Segmentation fault. – pedyram Jul 31 '22 at 05:14

0 Answers0