Click here to Skip to main content
16,018,496 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm getting the error:
HEAP CORRUPTION DETECTED: After Normal block (#247) at 0x003B98D0.
CRT detected that the application wrote to memory after end of heap buffer.

Here's the function that's causing the problem:
C#
String ^data::getItemNumber_noRev()
{
    int count = 0;
    while(itemNumber[count] != '_')
        count++;

    char *itemNum_noRev = new char[count];
    for(int i = 0; i < count; i++)
        itemNum_noRev[i] = itemNumber[i];

    itemNum_noRev[count] = '\0';

    gcroot<String ^> itemNum_noRev_system = gcnew String(itemNum_noRev);

    delete [] itemNum_noRev;

    return itemNum_noRev_system;
}


Basically it goes through a char array such as 12324736-1_6, where everything up to the underscore is the item number, and after is its revision. It is returned as a System::String^ because I'm using it in a Windows Form. The problem I'm having is with the line:
itemNum_noRev[count] = '\0';


When I don't include this line, I don't get an error, but I get about 10 magic characters at the end of my String. When I do include the line, that's when I get the heap corruption error.

Any ideas what to do to fix this? Thanks in advance for any advice!

Pat
Posted

1 solution

count is one past the last index, because it's 0 indexed. So make the size count+1, and you'll have room for your null terminator.
 
Share this answer
 
Comments
obp42 27-Jul-11 15:21pm    
I have actually tried that, and unfortunately I get the exact same error :(
Any other ideas?
obp42 27-Jul-11 15:23pm    
Nevermind, you're right.
When I first tried it I also changed the problem line to:
itemNum_noRev[count + 1] = '\0';
which is obviously wrong.
Thanks alot for your help!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900