Heap corruption

I'm getting a heap corruption and I don't understand why I am getting it.
In my main procedure I have the fallowing:
Main.cpp
1
2
3
4
5
6
wchar_t* tmp;
tmp = (wchar_t*)malloc((sizeof(arg[0])/sizeof(wchar_t)));
GetDirectory(arg[0],tmp);						
memcpy(p->cwd,tmp,wcslen(tmp)*sizeof(wchar_t));					
p->cwd = (wchar_t*)realloc(p->cwd,(wcslen(p->cwd)+1)*sizeof(wchar_t));
free(tmp);


formFuncs.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
void GetDirectory(wchar_t* Path,wchar_t* Dest)
{
	int i;
		
	for(i=wcslen(Path)-1;i>=0;i--)
	{
		if(Path[i]=='\\')
			break;			
	}
	if(i>0)
	{
		memcpy(Dest,Path,i*sizeof(wchar_t));
		//wcscpy(Dest,Path);
		Dest[i]='\0';
		return;
	}
	else
	{
		wcscpy(Dest,Path);
		return;
	}
}


I've tried wcscpy and memcpy both say that I am creating a HEAP corruption
Last edited on
 
tmp = (wchar_t*)malloc((sizeof(arg[0])/sizeof(wchar_t)));


Do you know what sizeof(arg[0]) returns?

Also you might benefit from using a std::wstring
yeah sizeof(arg[0]) returns 4....now I think I know why I'm getting it I should have used wcslen instead of size
 
tmp = (wchar_t*)malloc(((wcslen(arg[0])+1)*sizeof(wchar_t)));

I didn't want to use std::wstring because it doesn't resize the memory allocation(i'm trying to use the strict minimum)
Is there any reason you are using malloc() rather than new?
1
2
3
4
5
tmp = new wchar_t[wcslen(arg[0]) + 1)];

// ...

delete[] tmp;

?
Last edited on
Topic archived. No new replies allowed.