Search code examples
c++memorygets

Dynamic Memory allocation for char pointer


I have a strange issue related to dynamic memory allocation to char pointer. I have something like

char *input = new char; //1
gets(input) //2
char *dest = new char; //3

during the step3, i get heap corruption error during runtime. This only happens if the length of the string that i enter is more than 23 characters.

If i dont do any new operations, then there is no issue.

This issue is resolved if i specify

 char *input = new char[100]; 

But i want the input to be dynamic based on the user's input.

I am not sure what is the role of 24 bytes in this case. I dont want to limit to 100 or some n characters... I am kinda weak in memory allocation...Can somebody explain this scenario?


Solution

  • No, you can't do that way. You could use only static buffer or use "cpp-way", which is:

    std::string str;
    std::getline(std::cin, str);