Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problem with HeapAlloc()

Status
Not open for further replies.

lektrosonic

Programmer
Dec 16, 2007
1
FR
Hello,
I use Visual Studio 2008, and I have a problem with allocating memory on windows.
This is the part of my code:

char** split_data(char* cache,int bounds)
{
char** parts=NULL;
int i=0,j=0,len=0;
len=strlen(cache);
if(bounds<=0||len==0){return NULL;}
if(bounds>0&&len>0){parts=(char**)HeapAlloc(GetProcessHeap(),(HEAP_NO_SERIALIZE|HEAP_ZERO_MEMORY),sizeof(char*)*bounds);}
if(!parts){error(9,hwnd_main);}
parts[0]=cache;
for(i=0;i<=len;i++)
{
if(cache==SEP)
{
if(j==bounds)
{
cache=0;
break;
}
else
{
j++;
parts[j]=&cache[i+1];
cache=0;
}
}
}
return parts;
}

To explain:
cache parameter = "Jim~Maria~George~Mike~"
SEP = `~`
bound = 4
I want this fonction to return parts:
parts[0] = "Jim"
parts[1] = "Maria"
parts[2] = "George"
parts[3] = "Mike"

The strange thing is, that when I run my application by pushing the "Debug" button in Visual Studio, my function works, but when I run my application from Windows Explorer, either in Debug or Release, my application crushes:

A visual studio Just-in-Time debbuger windows appears
"An unhandled win32 exception occured in application_name.exe [3916]

Any idea on how to fix this issue ?

Thank you
 
Have you ever read HeapAlloc argument specification?
MS C++ Help said:
HEAP_NO_SERIALIZE
Specifies that mutual exclusion will not be used
while the HeapAlloc function is accessing the heap.
This flag should not be specified when accessing the
process heap. The system may create additional threads
within the application's process, such as a CTRL+C handler,
that simultaneously access the process heap.
Why simple malloc was not used?
It's a good job for standard library strtok() function...

Apropos, it's not a good style to allocate memory in a function then return a pointer to it. Better pass an array allocated by a callee.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top