c++ - Deletion of Dynamically Allocated Memory -


i have been given task, need create string_copy function note function body , prototypes have been given source , needs maintained. portions written me after comment write 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 string , long 1 can create memory leaks when copied , not deleted";      // write 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;     (const char* ptr = string; *ptr != '\0'; ++ptr) {         ++length;     }     return length; }  char* string_copy(const char* string) {     // need add 1 because of ’\0’     char* result = new char[string_length(string) + 1];      // write code here (remember zero-termination !)     int i;     (i = 0; string[i] != '\0'; ++i)     {         result[i] = string[i];     }     result[i] = '\0';     return result; } 

now task tells me

that important memory allocated e=new type released later delete e (and a=new type[size] delete [] a) else lead error.

it not clear if error means compile/runtime error or error in task did not meet requirement error.

my question is, in code how delete intermediate dynamically created result array? if delete result, won't fail purpose of task? how respect quotation above or maybe simulate memory leak given in long string constant?

thanks.

edit: why negative votes? please @ least explain reason! not asking solution or something, mere suggestion if missing point or not!

the caller of string_copy responsible releasing memory when it's done calling delete[] on it.

this is, way, terrible way write c++ code. should using std::string or std::vector<char> or 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

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -