Saturday, November 15, 2008

Strange behavior with this bit of C++

It has been a long time since I've had time to do anything in C++. So I figured it would be a useful way to limber up my memory, by implementing a little bit of my favorite Python classes/modules in C++. The only crazy thing, is the result this code has yielded.

// minimal program, using the code involved

extern "C" {
#include <sys/param.h>
#include <unistd.h>

namespace os {
    bool link(const std::string& src, const std::string& dst);

os::link(const std::string& src, const std::string& dst) {
    if (link(src.c_str(), dst.c_str()) != 0) {
        return false;
    return true;

main() {
    std::cout << "link()\t" << std::endl;
        os::link(std::string("./test"), std::string("/tmp/test"));
    return 0;

compilation: /usr/bin/g++ -Wall -ggdb3 os.cpp test.cpp -o test

I compiled on FreeBSD 7 with the systems GCC 4.3.1 and get a segfault, then tried the code on my OpenBSD 4.4 machine. The OpenBSD 4.4 release has shipped with a patched GCC 3.5.3 (propolice) - on OpenBSD it ran perfectly! Trying to feed it through the debuger on FreeBSD wasn't pretty either:

  • FreeBSD 7, system GCC 4.3.1 -> test program dies with a Segmentation Fault.
  • FreeBSD 7, system GDB 6.1.1 -> Endless stepping when used with a break point, or SIG SEGV in libc's malloc() when run.
  • OpenBSD 4.4, system GCC 3.5.3 -> prints proper message from std::perror() as expected, when the program is executed.

If I change os::link to os::link_x and recompile on FreeBSD, it works the same as it does on OpenBSD, when unmodified that is. In a few tests on FreeBSD, When I run the program under GCC, it tells me

Program received signal SIGSEGV, Segmentation fault.
0x281fabc3 in malloc () from /lib/

if I set a break point in test.cpp on the os::link() call, and step through it into os::link() in os.cpp. If I keep stepping after the link(), I get returned to the os::link() call in main and can step through it all again. Like an endless loop of stepping into/out of the os::link() function call in test.cpp's main(), and the if-conditional in os.cpp's os::link(), geeze.

At least looking at the results I've had tonight, I know I'm not freaking nuts... lol. I still shouldn't write code when I'm half asleep, but hey... It's the only time I get :\, Oh well... unless my family is late as usual, I need to be up in a few hour.

*head hits laptop, snores loudly until morning*

No comments:

Post a Comment