4

Is it safe when the request_token.size() is larger than LEN?

char dst[LEN];
memcpy(dst, request_token.c_str(), request_token.size());
amazingjxq
  • 4,487
  • 7
  • 33
  • 35

4 Answers4

8

No, it's not safe; you'll cause a buffer overflow. The reason is, memcpy has no way to know the size of your target buffer, other than the size you pass in the third argument.

C. K. Young
  • 219,335
  • 46
  • 382
  • 435
1

No, definitely not, that will lead to buffer overrun and trigger undefined behavior which will lead to all sorts of bad things, included but not limited to data corruption and program crashing.

sharptooth
  • 167,383
  • 100
  • 513
  • 979
1

No, it is not safe. Read this: http://msdn.microsoft.com/en-us/library/dswaw1wk(VS.80).aspx

Use memcpy_s(): http://msdn.microsoft.com/en-us/library/dswaw1wk(VS.80).aspx

bayCoder
  • 1,345
  • 1
  • 11
  • 19
  • 7
    memcpy_s is nonstandard and not portable. Just make sure you don't copy more than the buffer size. – interjay Jun 09 '11 at 08:22
  • 1
    It's also a crutch for people who have no right coding in C. If you don't want to learn how to use the tools properly, go back to BASIC :-) – paxdiablo Jun 09 '11 at 08:30
0

No, you will end up in trying to write to invalid memory locations which causes undefined behavior.

Naveen
  • 74,600
  • 47
  • 176
  • 233