help with free()

Started by
6 comments, last by petway56 21 years, 9 months ago
Was wondering if any of you could tell me why I get this error in MSVC 6.0 SP 5 on this stupid simple test program.
  
#include <stdio.h>
#include <stdlib.h>

#define TEST 5

int main(void)
{
	char *p;

	if (TEST == 5) 
		p = (char *)malloc((80 * sizeof(char)));
	p = "This is a test\n";
	if (p != 0) {
		printf("%s", p);
		free(p);
	}
	return 1;
} 

  
At the point where I try and free p I get a: Debug Assertion Failed! Program: test.exe File: dbgheap.c Line: 1011 Expression: _CrtIsValidHeapPointer(pUserData) Now this makes me think I''m passing an invalid pointer to free. But didn''t I test it both by checking for 0 status and printing the string it points to. Any help in clearing up my ignorance is appreciated!
Advertisement
does it fail on every run of the program. even when TEST == 5?

the first obvious problem is that you are not initializing the pointer to NULL. also, NULL != 0 in all cases. so set it to NULL:

char *p = NULL;

by stating char *p; pointer p is never initialized and, most likely will be junk data. thus you will enter the free statement because p != 0, but also, it has never been malloc'd.

[EDIT: obviously if you change the initialization to char *p = NULL; you also have to change the check before the free() block to:
if (p != NULL) { .... ]

-me

[edited by - Palidine on June 25, 2002 2:23:04 PM]
You''re setting p equal to the address of a temporary string (p = "This is a test\n"). If you''re going to use char arrays for strings, make sure you use the string functions (in this case strcpy). ie:

strcpy ( p, "This is a test\n" );

Otherwise, might I suggest std::string?
Thanks for the insight guys. Make sense now. I thought NULL was deprecated though and 0 is supposed to be used instead. Am I wrong on this, or is this true?
quote:I thought NULL was deprecated though and 0 is supposed to be used instead. Am I wrong on this, or is this true?


not entirely sure myself. i''m just pulling my suggestion from several other threads in which people have been flamed for setting pointers to zero instead of NULL. it had something to do with zeroth memory space as defined by different machines/compilers....don''t entirely remember.

-me
Hmm, something I''ll have to look into. Thanks again for the help.
From windows.h

  /* Define NULL pointer value */#ifndef NULL#ifdef  __cplusplus#define NULL    0#else#define NULL    ((void *)0)#endif#endif   


[edited by - terminate on June 25, 2002 5:13:17 PM]
Those who dance are considered insane by those who cannot hear the music.
Stroustrup recommends using 0 instead of NULL in C++ programs, since 0 is implicitly convertible to NULL.
---visit #directxdev on afternet <- not just for directx, despite the name

This topic is closed to new replies.

Advertisement