Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this being optimized away by g++? At least, I think that's what's going on

Tags:

c++

When I run the following code

#include <iostream>
int main(int argc, char *argv []) {
  
  std::string simpleString("this is just a simple string");
  
  std::cout << "simpleString = " << simpleString << std::endl << std::endl;
 
  std::string one = (simpleString + ", one");

  const char * oneCharStar = one.c_str();
  std::cout << "simpleString + one: '" << oneCharStar << "'" << std::endl;

  const char * twoCharStar = (simpleString + ", two").c_str();
  std::cout << "simpleString + two: '" << twoCharStar << "'" << std::endl;

  return 0;
}

on my Fedora Core 23 machine, on which uname -a reports:

"Linux glorp 4.5.7-202.fc23.x86_64 #1 SMP Tue Jun 28 18:22:51 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux"

and g++ --version says

"g++ (GCC) 5.3.1 20160406 (Red Hat 5.3.1-6)"

the first output reads "this is just a simple string, one", while the second output shows the empty string.

I guess there's some kind of optimization going on here, but, on my previous Ubuntu machine (16.mumble, rest in peace), this code ran as I would have expected. I just found that when I recompiled my application (using the same make files, etc) on the new machine, this code failed as above.

In addition, it works as I'd expect on the following platform as well:

$ uname -a Linux t4240rdb

3.12.37-rt51+g43cecda #2 SMP Fri Mar 4 18:18:03 EST 2016 ppc64 GNU/Linux

$ g++ --version

g++ (GCC) 4.9.2

Copyright (C) 2014 Free Software Foundation, Inc.

What's going on here? Thanks!

like image 498
nzc Avatar asked Jan 04 '23 19:01

nzc


1 Answers

const char * twoCharStar = (simpleString + ", two").c_str();

After this line, the temporary string (simpleString + ", two") is destroyed.

std::string allocates memory, and c_str() returns a pointer to that memory. In std::string's destructor, the memory is deallocated. Thus, after this line, twoCharStar points to deleted memory.

Using memory after it is freed is undefined behavior.

like image 58
Justin Avatar answered Feb 11 '23 07:02

Justin