0

I am trying to print size_t values using cout. Here is my code

#include <iostream>
using namespace std;
int main() {
  size_t blah = 15;
  cout << blah +" gibberish";
  return 0;
}

The output I get is this: D.

Thanks for the help! :)

*I am trying to use this to print memory usage.
*Also, what exactly is unit of size_t?
*I tried posting cout<<blah +" bytes"; which gives me a telephone Unicode emoji (U+0007 : BELL [BEL]) as the output but stackoverflow refuses to display it .

Sarwagya
  • 166
  • 11
  • clang has a nice warning for that: https://wandbox.org/permlink/lpowUUxwN3iiLbnh (unfortunately, no warning in gcc) – Yksisarvinen Aug 24 '20 at 14:08
  • "_what exactly is size unit of size_t_" `sizeof(std::size_t)` – Ted Lyngmo Aug 24 '20 at 14:09
  • @Yksisarvinen, there is a trick, you can trigger the warning by using optimization -O2 or -O3. – anastaciu Aug 24 '20 at 14:31
  • Accessing the `" gibberish"` C literal string at position 15 is past the end of the C literal string, and results in **undefined behavior**. The behavior observed is exactly the sort of undefined behavior that I'd expect, because I expect that *anything that happens* is expected for an invalid program. – Eljay Aug 24 '20 at 14:42
  • 1
    Note that this is not directly related to `std::size_t`. Any integer type would show the same problem. – Pete Becker Aug 24 '20 at 15:50

1 Answers1

4

blah +" bytes" is adding an integer to a pointer (converted from array of char), so the pointer is moved to invalid place.

You should do

#include <iostream>
using namespace std;
int main() {
  size_t blah = 15;
  cout << blah << " bytes";
  return 0;
}

instead. (use << instead of +: print the number and string one-by-one instead of trying to concatenate them beforehand)

MikeCAT
  • 73,922
  • 11
  • 45
  • 70