I ran into a problem, from an exercise in Bjarne Stroustrup's book Programming: Principles and Practice Using C++ (2nd edition), at the very end of chapter 17 for the Exercises section, exercise 7:
The program works normally if you do not use delete linearray1;
.
Accordingly, the problem is when deleting the allocated dynamic memory.
I have no error messages or warnings in the console.
However, VS Code shows me that problem in this line (delete linearray1
).
Highlights the entire line in yellow.
Tell me how to solve the problem in this case. How can I correctly clear the allocated memory?
#include <iostream>
void fillarray(std::string& array)
{
char* linearray1 {new char};
char* line = linearray1;
std::cin >> line;
while (*line)
{
if (*line == '!')
break;
array += *line;
line++;
}
delete linearray1;
}
int main()
{
std::string linearray1;
fillarray(linearray1);
std::cout << "\n" << linearray1;
return 0;
}
char* linearray1 {new char};
creates a pointer to a singlechar
. Why are you trying to mixstd::string
and manual memory management of c-style arrays?new
in a real C++ program in 13 years. Use smart pointers. The smart pointer for strings that manages the memory backing store for you is calledstd::string
.delete
. The problem is that you allocated only space for onechar
(basically, only enough to hold the NUL terminator), but tries to read a string fromcin
to it, which is UB and anything can happen. That removing thedelete
line makes the program appears to work proves nothing. It still has UB without thedelete
line.