New instead of Malloc

I've been working with a tutor on one of my assignments and within they had use me malloc. I am being told by my instructor that I should use new instead. In order to transition between the two, I want to make sure I am doing it correctly.

What I had (couple of examples);
1
2
3
4
5
  char* songTitle = (char*)malloc(sizeof(char)* 50);

  songTitle = (char*)malloc(sizeof(char)* 50);

  title = (char*)malloc(sizeof(char)* 50);


What I hope is correct on the transition;
1
2
3
4
5
  char* songTitle = new char[50]

  songTitle = new char[50]

  title = new char [50]


Am I correct on the transition? Or am I way off somehow? Full code is below.

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
#include "SongList.h"

SongList::SongList()
{
	totalSongsInFile = loadFile();
}

SongList::~SongList()
{
}

const int ARRAY_SIZE = 100;

void SongList::addSong()
{
	ofstream outputFile;
	char confirm;
	// Enter's new songs
	cin.ignore();
	cout << "What is the title of the song? " << endl;
	char* songTitle = (char*)malloc(sizeof(char)* 50);
	cin.getline(songTitle, 50);
	songTitle[0] = std::toupper(songTitle[0]);

	for (std::size_t i = 1; i < strlen(songTitle); ++i)
		songTitle[i] = std::tolower(songTitle[i]);

	cout << "Who is the artist?" << endl;
	char* songArtist = (char*)malloc(sizeof(char)* 50);
	cin.getline(songArtist, 50);

	songArtist[0] = std::toupper(songArtist[0]);
	for (std::size_t i = 1; i <strlen(songArtist); ++i)
		songArtist[i] = std::tolower(songArtist[i]);

	cout << "How long is the song? (i.e. 2:34) " << endl;
	char* songDuration = (char*)malloc(sizeof(char)* 50);
	cin.getline(songDuration, 50);
	songDuration[0] = std::toupper(songDuration[0]);

	for (std::size_t i = 1; i < strlen(songDuration); ++i)
			songDuration[i] = std::tolower(songDuration[i]);


	cout << "What is the name of the album? " << endl;
	char* songAlbum = (char*)malloc(sizeof(char)* 50);
	cin.getline(songAlbum, 50);
	songAlbum[0] = std::toupper(songAlbum[0]);

	for (std::size_t i = 1; i < strlen(songAlbum); ++i)
		songAlbum[i] = std::tolower(songAlbum[i]);


	cout << songTitle << " by " << songArtist << " on album " << songAlbum << ". Duration of song is " << songDuration << ". " << endl;
	do
	{
		cout << "Is this correct?(y/n): " << endl;
		cin >> confirm;
		switch (confirm){
		case'y':
		case'Y':
			break;
		case'n':
		case'N':
			cin.ignore();
			cout << "What is the title of the song? " << endl;
			songTitle = (char*)malloc(sizeof(char)* 50);
			cin.getline(songTitle, 50);
			songTitle[0] = std::toupper(songTitle[0]);

			for (std::size_t i = 1; i < strlen(songTitle); ++i)
				songTitle[i] = std::tolower(songTitle[i]);

			cout << "Who is the artist?" << endl;
			songArtist = (char*)malloc(sizeof(char)* 50);
			cin.getline(songArtist, 50);

			songArtist[0] = std::toupper(songArtist[0]);
			for (std::size_t i = 1; i <strlen(songArtist); ++i)
				songArtist[i] = std::tolower(songArtist[i]);

			cout << "How long is the song? (i.e. 2:34) " << endl;
			songDuration = (char*)malloc(sizeof(char)* 50);
			cin.getline(songDuration, 50);
			songDuration[0] = std::toupper(songDuration[0]);

			for (std::size_t i = 1; i < strlen(songDuration); ++i)
				songDuration[i] = std::tolower(songDuration[i]);


			cout << "What is the name of the album? " << endl;
			songAlbum = (char*)malloc(sizeof(char)* 50);
			cin.getline(songAlbum, 50);
			songAlbum[0] = std::toupper(songAlbum[0]);

			for (std::size_t i = 1; i < strlen(songAlbum); ++i)
				songAlbum[i] = std::tolower(songAlbum[i]);


			cout << songTitle << " by " << songArtist << " on album " << songAlbum << ". Duration of song is " << songDuration << ". " << endl;
			break;
		default:
			cout << "Invalid input. Please try again. " << endl;
			break;

		}

	} while (confirm != 'y' && confirm != 'Y');

	outputFile.open("songs.txt", ios::out | ios::ate | ios::app);
	outputFile << songTitle << "|" << songArtist << "|" << songDuration << "|" << songAlbum << "|";
	outputFile.close();
	outputFile.clear(std::ios_base::goodbit);
	totalSongsInFile = loadFile();

}

int SongList::showSongsByArtist()
{
	cin.ignore();
	cout << "Artist's Name: ";
	char* name = (char*)malloc(sizeof(char)* 50);
	cin.getline(name, 50);

	// Upper cases first word
	name[0] = std::toupper(name[0]);
	for (std::size_t i = 1; i < strlen(name); ++i)
		name[i] = std::tolower(name[i]);
	
	int a = 0;
	for (int i = 0; i < totalSongsInFile; i++){
		char* result = songs[i].getArtist();
		while ((result = std::strstr(result, name)) != NULL) {
			cout << songs[i].getTitle() << " written by " << songs[i].getArtist() << " on Album titled " << songs[i].getAlbum() <<
				". Length is " << songs[i].getDuration() << ". " << endl;
			a++;
			++result;
		}
	}
	if (a == 0){
		cout << "No artist found. " << endl;
	}
	return a;
}

int SongList::showSongsByAlbum()
{
	cin.ignore();
	cout << "Album Name: ";
	char* album = (char*)malloc(sizeof(char)* 50);
	cin.getline(album, 50);
	cout << " " << endl;
	album[0] = std::toupper(album[0]);

	for (std::size_t i = 1; i <strlen(album); ++i)
		album[i] = std::tolower(album[i]);

	int a = 0;
	for (int i = 0; i < totalSongsInFile; i++){
		char* result = songs[i].getAlbum();
		while ((result = std::strstr(result, album)) != NULL) {
			cout << songs[i].getTitle() << " written by " << songs[i].getArtist() << " on Album titled " << songs[i].getAlbum() <<
				". Length is " << songs[i].getDuration() << ". " << endl;
			a++;
			++result;
		}
	}
	if (a == 0){
		cout << "No album found. " << endl;
	}
	return a;
}
int SongList::loadFile()
{
	int count = 0;
	
	char* title;
	char* artist;
	char* duration;
	char* album;

	ifstream inFile;
	// Open File Error
	inFile.open("songs.txt");
	if (!inFile)
	{
		return -1;
	}else if (inFile)
	{
		while (true && count < ARRAY_SIZE)
		{
			title = (char*)malloc(sizeof(char)* 50);
			artist = (char*)malloc(sizeof(char)* 50);
			duration = (char*)malloc(sizeof(char)* 50);
			album = (char*)malloc(sizeof(char)* 50);
			
			inFile.getline(title, 50, '\|');
			songs[count].setTitle(title);
			inFile.getline(artist, 50, '\|');
			songs[count].setArtist(artist);
			inFile.getline(duration, 50, '\|');
			songs[count].setDuration(duration);
			inFile.getline(album, 50, '\|');
			songs[count].setAlbum(album);
			
			if (inFile.eof() == true)
				break;
			
			count++;
		}
		// Spits out record counts
		cout << count << " record(s) loaded successfully. " << endl;
		cout << " " << endl;
		return count;
	}
	inFile.close();
	inFile.clear(std::ios_base::goodbit);
	return 0;
}
//show All
void SongList::showAll()
{
	if (totalSongsInFile <= 0)
	{
		cout << "Nothing found! " << endl;
	}
	else{
		cout << " " << endl;
		int i = 0;
		for (i = 0; i < totalSongsInFile; i++)
		{

			cout << (i+1)<<". " << songs[i].getTitle() << " written by " << songs[i].getArtist() << " on Album titled " << songs[i].getAlbum() << ". Length is "
				<< songs[i].getDuration() << ". " << endl;
		}
		cout << " " << endl;
	}
	
}
void SongList::removeSong()
{
	ofstream outputFile;
	
	cin.ignore();
	char* album;
	cout << "Please enter the song title to remove: ";
	album = (char*)malloc(sizeof(char)* 50);
	cin.getline(album, 50);
	album[0] = std::toupper(album[0]);

	for (std::size_t i = 1; i <strlen(album); ++i)
		album[i] = std::tolower(album[i]);
	
	int index = -1;
	
	for (int i = 0; i < totalSongsInFile; i++){
		char* result = songs[i].getAlbum();
		while ((result = std::strstr(result, album)) != NULL) {
			index = i;
			++result;
		}
	}
	if (index==-1){
		cout << "No album found. " << endl;
	}
	else{
		outputFile.open("songs.txt", ios::out | ios::trunc);
		for (int i = 0; i < totalSongsInFile; i++){
			if (i != index){
				outputFile << songs[i].getTitle() << "|" << songs[i].getArtist() << "|" << songs[i].getDuration() << "|" << songs[i].getAlbum() << "|";
			}
		}
		cout << "\n\n" << songs[index].getTitle() << " has been removed!\n";
		outputFile.close();
		outputFile.clear(std::ios_base::goodbit);
	}

	totalSongsInFile = loadFile();
}
I would suggest you consider using std::string instead of the C-strings, then you won't need to worry about dynamic memory allocation at all.

Next if std::string is not an option, I would recommend that you use statically allocated arrays since you're using a constant size it doesn't really make sense to use dynamic memory.

Be careful about using the assignment operator= with C-strings, consider using something like strcpy() instead.

Why does line 190 have a while(true && XXX) ? Just make it while(XXX).

Not related to "malloc v. new" but in numerous places through out this code you make the common newcomer's mistake of using comparison to strlen() to drive a loop. Strlen() requires a variable amount of time to execute, so it should be replaced with a loop that uses a char* (or const char* if the cstring is const) in order to examine each char, like this:

1
2
3
4
5
6
7
//This loop is BAD! It works, but it slows things down a LOT...
for(size_t i=0; i < strlen(someStr); ++i)
   //Do something with someStr[i]...

//This loop is the best, it goes thru the array only once, while your doing something with the chars.
for(char* cursor=someStr; (*cursor); ++cursor)  //Or const char* if someStr is const.
   //Do something with (*cursor). 


Okay, back to malloc v. new: You seem to have the concept and differences right. The real differences are:
1) malloc obtains a number of bytes hence why you need "malloc( numberOfElements*sizeof(Element) )", while new[] gets elements so you only need "new Element[numberOfElements]".
2) malloc has no knowledge of type and returns a void*, so the cast is needed. new[] (and new for that matter) return an Element* so no cast needed.
3) new[] runs the default-constructor on all elements. Singular new can be told to run a non-default c-tor b/c it's obtaining a single element. malloc() leaves the bytes uninitialized and its up to you to initialize each one.
4) Technical: new[] may or may not store meta-data concerning the elements so that the call to delete[] can run the correct number of destructors. malloc() requires you to keep track of the number of elements and manually destroy each element BEFORE calling free() on the pointer.
5) new and new[] throw bad_alloc if they fail to obtain the memory and construct the elements. malloc() returns a nullptr. The only exception to this is if #include <new> is placed at the top of your file and 1 of:
1
2
new(std::nothrow) Element;  //Counts as a singular new
new(std::nothrow) Element[number];  //Counts as a compound new[] call. 

those is used. If 1 of those, or malloc(), is used you MUST check that the returned ptr is NOT null before using it!

Point #3 is a non-issue if your using built-in types like int, float, or other pointers, but it becomes a more important issue when using user-created data types.

Malloc() can be useful in some situations, but remember that new/new[] is most often preferable.
Last edited on
Thank you both on the advice and help. One more question, do I need to add in a delete[] to help prevent a memory leak? And if so, does this need to be done after each function?
Yes, anytime you allocate dynamic memory, you must release it using the right dealocation function (for new[], that would be delete[]). And it looks like when each of those functions concludes, the memory chunk is not needed, so I'm going to go with also yes ;).
Awesome! Thank you for your help on this one!
Topic archived. No new replies allowed.