-2

I want to allocate space for char array (string) in C++. When I allocate memory for 10 chars, I can also assign more characters to the char array. When I print it, it gives some of the additionally assigned characters from the array.

#include <string.h>

using namespace std;

int main()
{
    char *name = new char[10];

    strcpy(name, "MoreThanTenCharacters");

    cout << name << endl;
}

Although the allocated memory is for 10 characters, I can assign more. Printing gives exactly the same value. What is the logic behind it?

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
asgarov
  • 41
  • 6
  • 8
    You are invoking Undefined behavior. C++ does not do hand-holding regarding memory management, like other languages do. Why? Performance. Any kinds of checks = additional instructions = time spent on executing them. – Algirdas Preidžius Dec 07 '20 at 17:56
  • 4
    Best rule of thumb: **Never** manage memory manually using `new` and `delete` in c++, unless you're 100% sure that you need to, and what you're doing. For what you want to achieve use `std::string` period. Here's everything you need for dynamic memory management in c++: [1](https://en.cppreference.com/w/cpp/string), [2](https://en.cppreference.com/w/cpp/container), [3](https://en.cppreference.com/w/cpp/memory). – πάντα ῥεῖ Dec 07 '20 at 18:00
  • 1
    `` is a C header. In C++ you rather want to use `` and all the good stuff inside that (while the corresponding C++ header is ``) – 463035818_is_not_an_ai Dec 07 '20 at 18:01
  • 1
    Does this answer your question? [Undefined, unspecified and implementation-defined behavior](https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior) Look closely at the first example in the accepted answer. – Isaiah Dec 07 '20 at 18:04
  • This question may be received more positively if you explain what you **expected** your program to do. Do you think the program should print a message? Do you think `strcpy` should stop after 10 characters? Do you think the code should not compile? – Drew Dormann Dec 07 '20 at 18:08
  • @Isaiah That's not really a good duplicate for this question. The correct (closure) flag reason for _undefined behavior_ is the site specific _"**Not reproducible** or was caused by a typo"_. – πάντα ῥεῖ Dec 07 '20 at 18:19

1 Answers1

1

When the buffer pointed by the first argument is shorter than the string pointed by the second argument (taking the null terminator into consideration), then the copy will overflow the buffer into surrounding memory, and the behaviour of the program is undefined.

Printing gives exactly the same value. What is the logic behind it?

You've observed some behaviour. This is an example of possible behaviours that the program could have when the behaviour is undefined.

So, what is the correct way of allocating memory for JUST 10 chars and assigning a string to it?

Your allocation is correct although not ideal. Using a bare pointer is unsafe; in the end you leak the allocation. It's the copying where your bug happens.

An efficient and simple option is to use std::string. If your goal is to store the 10 character long prefix substring of the input, then following would be correct:

std::string name("MoreThanTenCharacters", 10);
eerorika
  • 232,697
  • 12
  • 197
  • 326
  • So, what is the correct way of allocating memory for JUST 10 chars and assigning a string to it? – asgarov Dec 07 '20 at 18:03
  • [`strcpy_s`](https://en.cppreference.com/w/c/string/byte/strcpy) if you need that precisely. But in C++, the usual thing to do is use a `std::string`, and eliminate the 10 char limit. – Mooing Duck Dec 07 '20 at 18:04
  • 1
    @asgarov don't you get it? You allocated 10 chars, then wrote more there than can fit, they were written only Richi know where. Best way to that is not doing that at all. Or you have to use c++ functionality, not the stdlib functions inherited from C. In wirst case is `strncpy`. Also, 10 char array can fit only string 9 characters long. – Swift - Friday Pie Dec 07 '20 at 18:10
  • @asgarov See edit. – eerorika Dec 07 '20 at 18:10
  • 1
    @MooingDuck Problem with `strcpy_s` is that it is non-standard in C++ and even in C it is optional and not implemented by all standard libraries (and the one implementation that does support it, doesn't even support the standard API as specified). – eerorika Dec 07 '20 at 18:17
  • @eerorika wait, MS imp;ementation is flawed? Didn't look into that. And it's while their compiler used to troll user into applying those – Swift - Friday Pie Dec 07 '20 at 18:34
  • @Swift-FridayPie IIRC, there's something about registering the constraint handler that's non-conforming. – eerorika Dec 07 '20 at 18:44
  • @asgarov _"So, what is the correct way ..."_ Using `new` certainly isn't for your case, [YAGNI](https://stackoverflow.com/questions/65186856/dynamic-memory-allocation-in-c-language?noredirect=1#comment115243745_65186856) – πάντα ῥεῖ Dec 07 '20 at 18:51