0
const myName = "BlueBug";
char* name = new char[strlen(string) + 1]; //allocate spaces
strcpy_s(newLine, strlen(string)+1,  string); //Tada! perfect
//Hey but what if... I do this?

const myNewName = "SuchAVeryLongNameIHave";
strcpy_s(name, strlen(myNewName ) + 1, myNewName ); 
// 

I am copying my new name to, starting from the location in which....

my previous name has started, but my previous name is a lot shorter than myNewName

Shouldn't i be yelled at because my previous name was BlueBug, so I only allocated 8 character lengths... but I am now writing 10+ characters without allocating space

Blue Bug
  • 149
  • 6
  • 1
    `strlen(string)`: did you mean `strlen(myName)`? – Nate Eldredge Apr 18 '21 at 17:50
  • **Absolutely unsafe.** At best undefined behavior. In practice, you are likely to corrupt the heap as you overwrite past the original allocation length and stomp on top of other bytes in the heap, a previous allocation, or a future allocation (that will surely result in your string getting overwritten). Debug builds of some compilers might crash earlier to warn you, but definitely not guaranteed. – selbie Apr 18 '21 at 17:51
  • (1) Yes, your code is buggy and causes undefined behavior. (2) No, the language provides no guarantee that you will be "yelled at"; rather such code will tend to fail intermittently and unpredictably, but it also may appear to work at times. See https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior. – Nate Eldredge Apr 18 '21 at 17:51
  • Does this answer your question? [Accessing an array out of bounds gives no error, why?](https://stackoverflow.com/questions/1239938/accessing-an-array-out-of-bounds-gives-no-error-why) – Nate Eldredge Apr 18 '21 at 17:54
  • `strcpy_s(name, strlen(myNewName ) + 1, myNewName )` is not safe since you use the length of the string in `myNewName`, which might be longer than the memory allocated for `name`. – Some programmer dude Apr 18 '21 at 17:56
  • 3
    The length that you pass to `strcpy_s` should be the length of the **destination**; the function figures out the length of the source on its own. – Pete Becker Apr 18 '21 at 18:00

0 Answers0