I'm relatively novice when it comes to C++ as I was weened on Java for much of my undergraduate curriculum (tis a shame). Memory management has been a hassle, but I've purchased a number books on ansi C and C++. I've poked around the related questions, but couldn't find one that matched this particular criteria. Maybe it's so obvious nobody mentions it?
This question has been bugging me, but I feel as if there's a conceptual point I'm not utilizing.
Suppose:
char original[56];
cstr[0] = 'a';
cstr[1] = 'b';
cstr[2] = 'c';
cstr[3] = 'd';
cstr[4] = 'e';
cstr[5] = '\0';
char *shaved = shavecstr(cstr);
// various operations, calls //
delete[] shaved;
Where,
char* shavecstr(char* cstr)
{
size_t len = strlen(cstr);
char* ncstr = new char[len];
strcpy(ncstr,cstr);
return ncstr;
}
In that the whole point is to have 'original' be a buffer that fills with characters and routinely has its copy shaved and used elsewhere.
To clarify, original is filled via std::gets(char* buff)
, std::getline(char* buff, buff_sz)
, std::read(char* buff, buff_sz)
, or any in-place filling input reader. To 'shave' a string, it's basically truncated down eliminating the unused array space.
The error is a heap allocation error, and segs on the delete[]
.
To prevent leaks, I want to free up the memory held by 'shaved' to be used again after it passes through some arguments. 开发者_JAVA技巧There is probably a good reason for why this is restricted, but there should be some way to free the memory as by this configuration, there is no way to access the original owner (pointer) of the data.
I assume you would replace original
by cstr
, otherwise the code won't compile as cstr
is not declared.
The error here is that the size of the allocated array is too small. You want char* ncstr = new char[len+1];
to account for the terminating \0
.
Also, if you delete shaved
right after the function returns, there is no point in calling the function...
[*] To go a bit deeper, the memory used for cstr
will be released when the containing function returns. Usually such static strings are placed in constants that live for the entire duration of the application. For example, you could have const char* cstr="abcde";
outside all your functions. Then you can pass this string around without having to dynamically allocate it.
Assuming you meant to use cstr
instead of cstrn
...
You should not be deleting cstr
. You should be deleting shaved
.
You only delete
the memory that was allocated with new
. And delete[]
memory that was allocated with new[]
.
shaved
is simply a variable that holds a memory address. You pass that memory address to delete[]
to get rid of the memory. shaved
holds the memory address of the memory that was allocated with new[]
.
精彩评论