malloc crash

Hi all,

I have written a simple program that runs OK within Visual Studio 10 (both Debug and Release), but it crashes when I run the program directly from the command line.

I think I have narrowed it down to malloc, but the crash doesn't make sense to me.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int main(int argc, char **argv) {
	const char *conformSuffix = " - conform.pcap";
	const char *exceedSuffix = " - exceed.pcap";
	char *conformFileName,*exceedFileName;
	int mallocBytes;

	mallocBytes = strlen(argv[1])+strlen(conformSuffix);
	printf("About to malloc %d bytes for File Name\n",mallocBytes);
	conformFileName = (char*)malloc(mallocBytes);
	sprintf(conformFileName,"%s%s",argv[1],conformSuffix);
	file1 = pcap_dump_open(fp,conformFileName);
	if (file1 == NULL) {
		fprintf(stderr,"\nUnable to open the file %s.\n", conformFileName);
		return -2;
	}
	printf("Conform File Open\n");
	mallocBytes = strlen(argv[1])+strlen(exceedSuffix); 	
	printf("About to malloc %d bytes for File Name\n",mallocBytes);
	exceedFileName = (char*)malloc(mallocBytes);
	printf("Malloc Complete\n");
}


The output I see on screen is:


About to malloc 24 bytes for File Name
Conform File Open
About to malloc 23 bytes for File Name


Then it crashes

I am a bit stuck to be honest!
I have worked it out! I wasn't allowing the extra byte for the NULL termination in the string, so the program was writing to invalid memory.

Does anyone know:

1) Why only the second instance caused a problem?
2) Given that it was actually code following the last line shown on my snippet, why the "Malloc Complete" line wasn't printed?
file1, fp, and pcap_dump_open aren't declared; what header files have been chopped off the top?
Topic archived. No new replies allowed.