0

I don't mean to use this code in production environment, but I'm a little confuse about it.I thought it must be undefined,however,I ran this code without crash.Is this just conincidence?

#include <array>
#include <string>

auto main(int argc, char** argv) -> int {
  // for (int i = 0; i < 1000; ++i) {
  std::array<char, 1000> dst;
  std::string src = "hello world";
  memcpy(dst.data(), src.c_str(), dst.size()); // is this undefined behavior?
  // }
}

maidamai
  • 712
  • 9
  • 26
  • 3
    Undefined behavior does not mean "guaranteed crash" – StoryTeller - Unslander Monica May 25 '20 at 07:55
  • @StoryTeller-UnslanderMonica So I asked `Is this just conincidence?` – maidamai May 25 '20 at 07:56
  • 2
    It is undefined behaviour, and undefined behaviour can mean a failure to crash. I'm not sure I'd describe that situation as a coincidence though. It just regular undefined behaviour. – john May 25 '20 at 07:58
  • 1
    fyi Undefined Behaviour can cause Time Travel https://stackoverflow.com/questions/24527401/undefined-behavior-causing-time-travel – Richard Critten May 25 '20 at 08:11
  • _Is it just coincidence?_ This question is generally unanswerable. It may be a coincidence, it may not. One would need to study the generated assembly, at least. At the assembly level, it's possible that nothing illegal happens. – Daniel Langr May 25 '20 at 08:15

1 Answers1

2

I thought it must be undefined

Yes, it is undefined behaviour. src.data points to an array of 12 chars (=12 bytes), but memcpy will attempt to read 1000 bytes from it, so it reads out of bounds.

however, I ran this code without crash

That's the point of undefined behaviour. Anything might happen. This includes running without any problems at all.

Lukas-T
  • 11,133
  • 3
  • 20
  • 30