do I must release this memory?

Hi Guys,

Please see following code.

#include <iostream>
#include <string>
using namespace std;

int main(int argc, char* argv[]) {

string* s = new string[3];
s[0] = "str1";
s[1] = "str2";
s[2] = "str3";

delete [] s; // do I must do this?

return 0;
}

Do I must "delete [] s;" ?

I ask because I saw some legacy code I am working on didn't "delete [] s;". Does it cause memory leak?

Thanks!
// do I must do this?

Yes. every new[] must have a matching delete[]

Does it cause memory leak?


Yes.
if you don't delete, your array will just be floating around ... lost in space ... or RAM and you will lose access to it FOREVER haha but If the code is small enough (ex a class project) its not gonna make a big difference. It is technically a memory leak though
Thanks for your answers? Just one more question.

Does that array still occupy the memory even the program is finished?

Thanks
It depends on your OS and (possibly) the current set of neutrinos flying through your computer.
Thanks! the program is running in Linux (centos 5), does it matter?
string* s = new string[3]; You shouldn't be doing that in the first place.
Use string s[3]; instead
Hi Guys,

All my fault, I should provide you the accurate scenario. Currently I am debugging a legacy c++ program which runs in linux OS. The program invokes a class static member function to get a db connection setting.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <string>
using namespace std;

class DbSetting {
	public:
		static string* getDbSettings();
};

string* DbSetting::getDbSettings() {
	string* settings = new string[4];
	settings[0] = "dbname";
	settings[1] = "server";
	settings[2] = "username";
	settings[3] = "password";
	return settings;
}

int main(int argc, char* argv[]) {
	
	string* dbSettings = DbSetting::getDbSettings();
	
	//dbSettings is used to construct a db connection string

	return 0;
}


"dbSettings" is used to construct a db conneciton string but it never being "delete[] dbSettings" in "main" function. Such usage exists in some of other c++ legacy programs, I am not sure if I should report it as a bug of memory leak?

Many thanks!
Topic archived. No new replies allowed.