Heap corruption while freeing memory

I have following code in which I am getting "Heap corruption detected" message while trying to freeing memory allocated using strdup().

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
#include <iostream>
#include <string>
#include "Check.h"


static void main()
{

	
for (int i = 0;i< 5 ;i++)
{
char cname[32];
cname = GetGroupName()//These function assigns name here
bool exist;
	exist =	GetGroupStatus(cname);
}

}

bool GetGroupStatus(char *cname)
{
	char * cTemp = NULL;
	cTemp = _strdup(cname);
	bool bGrpStatus; 
	size_t found;

	//some code here

	std::string sTemp = cTemp;
	
	found = sTemp.find("GROUP");

	if (found != string::npos)
		bGrpStatus = true;
	else
		bGrpStatus = false;

	if (cTemp  != NULL)
	free(cTemp);	//These causes heap corruption detected message when control comes here second time

	return bGrpStatus; 
}


Please let me know what I am missing?
Last edited on
cTemp = _strdup(cname); What does that function do?
If the memory was not dynamic allocated, you must not free it.
Last edited on
HOw can we check whether memory is allocated or not?
I guess check for (cTemp != NULL) should suffice.
Would you like to suggest any changes.
When you free some memory using free(), the pointer does not get changed. It will still point to the exact same place in memory. It is up to you to manually set it to NULL. You are not doing this in your code above.

http://www.cplusplus.com/reference/clibrary/cstdlib/free/

"Notice that this function leaves the value of ptr unchanged, hence it still points to the same (now invalid) location, and not to the null pointer."
HOw can we check whether memory is allocated or not?
You can't (at least you use invariants of a class). However you need to know if the memory was allocated with malloc, calloc, realloc, to be freed with free.
1
2
3
int array[100];
int *ptr = array;
delete [] ptr; //error 
Topic archived. No new replies allowed.