Heap Corruption in C++

Hello Everyone,
I have one socket client c++ program it has some heap corruption in that. i m not understanding where this is happening

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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
#include <stdio.h>
#include <stdlib.h>
#include <winsock2.h>
#include <string.h>
#include <windows.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#include <process.h>
#include <dos.h>
#include <clocale>
#include <cstdio>
#include <locale>

#include "dirent.h"

#define DEFAULT_PROTO SOCK_STREAM

char *server_name = (char*) malloc (256); 
char *portasstring = (char*) malloc (64); 
char *formatasstring = (char*) malloc (64);
char *storefilename=(char*) malloc (2048);
char *speedline=(char *) malloc (64);
char *sleeptime=(char *) malloc (64);
char *nooflineattime=(char *) malloc (64);
char basePath[MAX_PATH];



void handlefile(char* filepath)
{
	try 
	{
			FILE *fsetup;
			FILE *fHIST, *hist;
			char ch, hch;
			char *line;
			char *readLineNumber; 
			int hcnt, cnt, linecnt, totallinecnt;	
			char *filetemp;
			char *histPath;
			char *path = (char*) malloc (255);
			char *drive = (char*) malloc (255);
			char *dir = (char*) malloc (255);
			char *fname =(char*) malloc (255);
			char *ext = (char*) malloc (255);
			int i;
			int sentLines;
			SYSTEMTIME str_t;
			GetSystemTime(&str_t);
			_splitpath(filepath,drive,dir,fname,ext);

			sentLines=0;
			cnt=0;
			hcnt=0;
			linecnt=0;
			totallinecnt = 0;
			histPath = (char*) malloc (255);
			filetemp = (char*) malloc (255);
			readLineNumber = (char*) malloc (255);
			readLineNumber[0] = '\0';
			line = (char*) malloc (51200);
			line[0] = '\0';

	
			fsetup = fopen(filepath,"r");
	
			if(fsetup != NULL)
			{
				sprintf(histPath,"%sHIST\\%s.HIST", basePath,fname);
				/* open a hist file which is created now */
				hist = fopen(histPath,"r");
				if(hist != NULL)
				{

					while(1)
					{
						hch = fgetc(hist);
						if(hch == EOF) break;
						readLineNumber[hcnt++] = hch;
						readLineNumber[hcnt] = '\0';

					}
					fclose(hist);
				}
		
				i=0;
				while(i < strlen(formatasstring))
				{
					line[cnt++] = formatasstring[i++];
				}
				line[cnt] = '\0';
		
				while(1)
				{
					ch = fgetc(fsetup);
					if(feof(fsetup))
					{
						//printf("feof\n");
						break;
					}
					else if(ch=='\n')
					{
						linecnt ++;
						totallinecnt ++;
						if(linecnt ==atoi(nooflineattime))
						{
							line[cnt++] = ch;
							line[cnt]='\0';
							if(totallinecnt > atoi(readLineNumber))
							{
								if(sendline(line)==0)// check for socket connection is open or no.
								{
										sentLines++;
									//	printf("sentlines--> %d\n\n",sentLines);
										sprintf(filetemp,"%d\0", totallinecnt);
										fHIST = fopen(histPath,"w");
										fwrite(filetemp, strlen(filetemp),1,fHIST);
										fclose(fHIST);
								}else
								{
									printf("socket no t open\n");
									break;
								}
								if(sentLines > atoi(speedline))
								{
									break;
								}
							}
							else
							{

								Sleep(atoi(sleeptime));
							}
							//free(line);
							//line= (char*) malloc (51200);
							line[0] = '\0';
							cnt = 0;
							i=0;
							while(i < strlen(formatasstring))
							{
								line[cnt++] = formatasstring[i++];
							}
							line[cnt] = '\0';
							linecnt = 0;
						}
						else
						{
							line[cnt++] = ch;
							i=0;
							while(i < strlen(formatasstring))
							{
								line[cnt++] = formatasstring[i++];
							}
							line[cnt] = '\0';

						}
					}
					else
					{
						line[cnt++] = ch;
						line[cnt] = '\0';
					}
				}	
			}
			else
			{
		
			}
			free(path); 
			free(drive); 
			free(dir); 
			free(fname);
			free(ext); 
			free(histPath);
			free(filetemp);
			free(readLineNumber); 
			free(line); 
			fsetup=NULL;
			fHIST=NULL;
			hist=NULL;
	}catch(char * str)
	{
			WriteError(str);
	}
	
	}

unsigned _stdcall createthreadtohandlefile(void* pfilename)
{
	try
	{
		char *filename = (char*)pfilename;
		char *createtemp;
		createtemp = (char*) malloc (255);
		createtemp[0] = '\0';
		sprintf(createtemp,"%s",filename);
	
		handlefile(createtemp);
	
		free(createtemp);
     	_endthreadex(0);	
	}catch(char * str)
	{
			WriteError(str);
	}
	return 0;
}

void handlefolder(char* dirpath)
{
	try {
		DIR *dir;
		struct dirent *ent;
		char* foldertemp;
		HANDLE handle[100];
		int i,n,nooffiles=0;
		dir = opendir (dirpath);
		if (dir != NULL) 
		{

			while ((ent = readdir (dir)) != NULL) 
			{
					switch (ent->d_type) 
					{
						case DT_REG:
				
							foldertemp = (char*) malloc (255);
							foldertemp[0] = '\0';
							sprintf(foldertemp,"%s\\%s",dirpath,ent->d_name);
							if(strstr(foldertemp,".log"))
							{
							handle[nooffiles] =  (HANDLE)_beginthreadex( NULL, 0, &createthreadtohandlefile, foldertemp, 0, NULL);
							//	handle= (HANDLE) _beginthread(createthreadtohandlefile,0,foldertemp);// create thread
								nooffiles++;
								Sleep(1000L);
							}
							break;

						case DT_DIR:
							break;

						default:
							break;
					}
			}	
			
			closedir (dir);
		} 
		else 
		{
			perror ("no dir");
		}
	//	Sleep(200);
		//WaitForSingleObject(handle,INFINITE);
	    WaitForMultipleObjects(nooffiles,handle, TRUE, INFINITE);
	    CloseHandle( handle );
		
		dir = NULL;
		free(foldertemp);	
	}catch(char * str)
	{
		WriteError(str);
	}
}

int main()
{

	FILE *fsetup;
	char ch;
	char *path, *setupFileName;
	int cnt, linecnt;

	char *drive = (char*) malloc (255);
	char *dir = (char*) malloc (255);
	char *fname =(char*) malloc (255);
	char *ext = (char*) malloc (255);
	int i;
	TCHAR szPath[MAX_PATH];
	GetModuleFileName( NULL, szPath, MAX_PATH );
	
	wcstombs(basePath, szPath, sizeof(basePath));
	

	_splitpath(basePath,drive,dir,fname,ext);
	sprintf(basePath,"%s%s",drive,dir);

	try{
		cnt=0;
		linecnt=0;
		path = (char*) malloc (160);
		setupFileName = (char*) malloc (256);
		path[0] = '\0';
		storefilename[0] = '\0';
		sprintf(setupFileName,"%ssetup.ini",basePath);
		fsetup = fopen(setupFileName,"r");
		if(fsetup != NULL)
		{

			while(1)
			{
				ch = fgetc(fsetup);
				if(ch==EOF)
				{
					handlefolder(path);
					break;
				}
				else if(ch=='\n')
				{
					linecnt++;
					if(linecnt == 1) 
					{
						sprintf(server_name,"%s",path);
					}
					else if(linecnt == 2) 
					{
						sprintf(portasstring,"%s",path);
					}
					else if(linecnt == 3) 
					{
						sprintf(formatasstring,"%s ",path);
					}	
					else if(linecnt == 4) 
					{
						sprintf(nooflineattime,"%s ",path);	
					}
					else if(linecnt == 5) 
					{
						sprintf(speedline,"%s ",path);
					}
					else if(linecnt == 6) 
					{
						sprintf(sleeptime,"%s ",path);
					}
					else
					{
						handlefolder(path);
					}
					path[0] = '\0';
					cnt = 0;
				}
				else
				{
					path[cnt++] = ch;
					path[cnt] = '\0';
				}
			}	
		}
		
	}catch(char * str)
	{
			WriteError(str);
	}
	fsetup = NULL;
	free(path);
	free(server_name);
	free(portasstring);
	free(formatasstring);
	free(storefilename);	
	return 0;
	
}



this is the error

Faulting application name: CollationaAgent1.exe, version: 0.0.0.0, time stamp: 0x506c10be
Faulting module name: CollationaAgent1.exe, version: 0.0.0.0, time stamp: 0x506c10be
Exception code: 0xc0000417
Fault offset: 0x0000409e
Faulting process id: 0x2234
Faulting application start time: 0x01cda15071db8dce
Faulting application path: E:\00ISAC\03Projects\Client\Carwale\Code\CollationAgent\server1\CollationaAgent1.exe
Faulting module path: E:\00ISAC\03Projects\Client\Carwale\Code\CollationAgent\server1\CollationaAgent1.exe
Report Id: bbc0d896-0d43-11e2-b40e-001fe2129807
closed account (zb0S216C)
You're freeing memory that does not exists. Before attempting to free a block of memory, always check the pointer for "NULL", and always set a freed pointer to null.

Wazzak
Last edited on
In main():
- you never close fsetup
- you never free:
setupFileName
drive
dir
fname
ext

There's a lot of bad practice going on regarding memory mangement. Clearly, you can't write code this way.
Dear Framework,

where exactly you are talking about.?
Dear KBW,

Thanks for your reply

I m beginner C++ so please excuse my code and where were i m wrong please correct me.

I want your more help to make this code perfect


Clearly, you're using C++ and not C. So:
1. use std::string when you need strings
2. declare variables where they're used
3. if the buffers are small, declare them on the stack
4. if the buffers are large, wrap them in a class that releases them. Minimally, there's std:auto_ptr<>, but there are newer and better newer standard ones
5. use the C++ stream library to handle files rather than ANSI C file functions
6. use C++ casts rather than C casts

Think more about your program logic and system limits.
1. What happens if your directory has more than 100 files?
2. How many objects can you wait for with WaitForMultipleObjects?
4. You don't close thread handles after the wait.
3. You catch const char*, but never throw one.

I hope that helps.
Dear Kbw,

Thank for your reply.
Topic archived. No new replies allowed.