jeudi 7 juin 2018

Odd behaviour of g++ and clang++ with enabled optimization

Here's my program:

print.hpp:

#pragma once

#include <iostream>

template<size_t p>
void print()
{
  std::cout << "" << __FILE__ << "" <<  __LINE__ << "" << std::endl;
  exit(0);
}

print.cpp:

#include "print.hpp"

template<>
void print<13>()
{
  std::cout << "Unlucky." << std::endl;
}

main.cpp:

#include <iostream>
#include "print.hpp"

int main()
{
  std::cout << "Started." << std::endl;
  print<13>();
  std::cout << "Exiting." << std::endl;
}

When I compile that with g++ main.cpp print.cpp -O0 -std=c++11 && ./a.out it works fine (output is:

Started.
Unlucky.
Exiting.

). However, if'd I compile that with g++ main.cpp print.cpp -O1 -std=c++11 && ./a.out it would give me a segmentation fault with the output:

Started.
Hi
Speicherzugriffsfehler //German for memory access error

Almost the same with clang++, without optimization it would do its job just fine and with -O1 or higher it outputs that:

Started.
Unlucky.
./print.hpp8

Why is that?

Aucun commentaire:

Enregistrer un commentaire