Deleting a non-owned dynamic array through a pointer

Posted by ayanzo on Stack Overflow See other posts from Stack Overflow or by ayanzo
Published on 2010-04-12T04:00:40Z Indexed on 2010/04/12 4:03 UTC
Read the original article Hit count: 343

Filed under:
|
|
|
|

Hello all, 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);
delete[] cstrn;

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 prevent leaks, I want to free up the memory held by 'shaved' to be used again after it passes through some arguments. 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.

© Stack Overflow or respective owner

Related posts about c++

Related posts about simple