Archived

This topic is now archived and is closed to further replies.

help with free()

This topic is 5647 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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!

Share this post


Link to post
Share on other sites
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]

Share this post


Link to post
Share on other sites
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?

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites