You're allocating a single char instead of an array. Use:
char* ptr;
ptr=new char[65];
strcpy(ptr,"asdf");
delete[] ptr;
As it is now, you're writing the first a
to the allocated char, and the rest on some arbitrary memory that was never allocated to you. The runtime detects that (on debug build), and complains.
Making my comment to the question part of my answer:
C++ doesn't have any mechanism to identify the potential error in the question's code. The only way for a compiler to know the size of the buffer that is passed to strcpy
is using static analysis, and that may or may not work. But even if it does, the compiler doesn't know the semantics of strcpy
. So at compile time, it can't warn you about the error.
Now, when the buffer is passed tostrcpy
at runtime, strcpy
has no way to tell how large is that buffer. So it just assumes the caller provided a suitable buffer, and goes ahead with the copy. If you're lucky, overflowing the allocated buffer will cause an immediate crash due to a write to unallocated page. If not, you'll get a memory corruption.
The error you do get is the result of a mechanism used on debug builds: the memory manager allocates a few more bytes than what you ask, and writes a special pattern onto them. Then, when the allocated memory is freed, it checks whether that pattern still exists. If not, it complains the user's code has written onto them. In release builds, you don't have those extra checks, and such bugs may cause a corruption without being noticed.
The only way to avoid such cases is to write safer code:
- Use higher-level constructs like
std::string
. They do the memory management for you, and save you from having to deal with low-level string functions.
- Use Microsoft's (non-standard) safe variants - strcpy_s, for example. Those functions take the size of the buffer as well, and fail if it is insufficient - without doing any damage.
- Use (standard) strncpy, pass the buffer's size as the last argument, and check the return value to see how many chars have been copied. As with the previous suggestion, specifying a wrong buffer size will still cause damage.
- Bear in mind that if you want to shoot your own toes, C++ will gladly hand you a down-pointing gun. Dealing with raw buffers, pointers and low-level string functions has to be done with care. The language will not save you from your own mistakes.