Memory leak

In lines 25 & 35, I bail from application before CBuffer is established.

CBuffer is determined in line 39, but like a bad lama I modify it in 44 and therefore in 56 where I should be freeing it, CBuffer is no longer the same.

My question out of curiosity sake is will exit (0) in 68 clean this up, or will this cause a memory leak?

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
#include		<stdio.h>
#include		<stdlib.h>

	char	*CBuffer;
	int		Values [26];
	
/* Applications entry point */
int main ( int ArgV, char *ArgC [] ) {

	char		*FileNme;
	
	printf ( "\n\nParseTxt 1.0 - 2012 - 05 - 04\n");
	
	/* First we must determine if operator passed a filename to application.  The assumption will be the only parameter passed */
	if ( ArgV > 1 ) {
		FILE *Data;
		unsigned FileSize, Threshold = 0;
		
		FileNme = ArgC [1];
		printf ( "\tOpening %s", FileNme );
		Data = fopen ( FileNme, "rb");
		
		if ( !Data ) {
			printf ( " failed\n\n");
			return -1;
			} /* Failed to open data file
			
		/* Determine size of file */
		fseek ( Data, 0, SEEK_END );	/* find end of file */
		FileSize = ftell ( Data );
		fseek ( Data, 0, SEEK_SET ); /* Go to beginning of file again */
		
		if ( !FileSize ) {
			printf ( " but is empty\n" );
			return -2;
			}
			
		printf ( " that has %d Bytes", FileSize );
		CBuffer = (char *) malloc ( FileSize );
		int Bytes_Read = fread ( CBuffer, 1, FileSize, Data );
		fclose ( Data );		
		
		for ( int Cnt = 0; Cnt < Bytes_Read; Cnt++ ) {
			char Ch = *CBuffer++;
			Ch &= 0x5F;
			
			if ( Ch >= 'A' && Ch <= 'Z' ) {
				Ch -= 'A';
				Values [Ch]++;
				
				if ( Values [Ch] > Threshold )
					Threshold = Values [Ch];
				}
			}
		
		// free ( CBuffer );
			
		printf ( "Threshold is: %d\n\n", Threshold );
		
		for ( FileSize = 0; FileSize < 26; FileSize++ ) 
			printf ( "[%c] -- %d\n", FileSize + 'A', Values [FileSize] );
						
		printf ( "\n\nDone\n" );
		} /* A filename was passed to application */
	else
		printf ( "\tYou must specify file in prompt string\n");		
	
	exit (0);
	}
Modern OS's will free all allocated memory by the process once the process ends. So no you won't leak memory in that sense.

I still would not recommend this style of coding, though.
I was aware of this in the Windows environment, but as I've just switched all my stuff to Linux I was curious if the same applied. I don't generally bang something as shoddy as this, but as it only has a one time use, when I got the error messages, I was curious.

Thanks Disch
Topic archived. No new replies allowed.