Jeet.Deir Jeet.Deir - 28 days ago 11
C++ Question

Deletion of Dynamically Allocated Memory

I have been given a task, where I need to create the string_copy function Note that the function body and prototypes have been given by the source and that needs to be maintained. The portions written by me are after the comment

write your code here
.

#include <iostream>
using namespace std;
int string_length(const char* string_c);
char* string_copy(const char* string_c);

int main()
{
const char* string_c = "This is a string and is a long one so that we can create memory leaks when it is copied and not deleted";

// write your code here
int length = string_length(string_c);
cout << "Copied String: " << string_copy(string_c) << endl;
return 0;
}

int string_length(const char* string) {
int length = 0;
for (const char* ptr = string; *ptr != '\0'; ++ptr) {
++length;
}
return length;
}

char* string_copy(const char* string) {
// we need to add 1 because of ’\0’
char* result = new char[string_length(string) + 1];

// write your code here (remember zero-termination !)
int i;
for (i = 0; string[i] != '\0'; ++i)
{
result[i] = string[i];
}
result[i] = '\0';
return result;
}


Now task tells me


that it is very important that any memory allocated with e=new TYPE is
released later with delete e (and a=new TYPE[size] with delete [] a)
else this will lead to an error.


It is not exactly clear if error means
compile/runtime error
or error as in my task did not meet the requirement error.

My question is, in this code how do I delete the intermediate dynamically created
result
array? If I delete
result
, won't it fail the purpose of the task? Then how am I to respect the quotation above or maybe simulate memory leak as given in the
long
string constant?

Thanks.

EDIT: Why the negative votes? Please at least explain the reason! I am not asking any solution or something, but mere suggestion if I am missing some point or not!

Answer

The caller of string_copy would be responsible for releasing the memory when it's done with it by calling delete[] on it.

This is, by the way, a terrible way to write C++ code. You should be using std::string or std::vector<char> or something like that.

Here's why:

int length = string_length(string_c);
char* copy = string_copy(string_c);
cout << "Copied String: " << copy << endl;
delete[] copy;
return 0;

Yuck.

Comments