heap corruption detected after delete call in visual c++?

945 views Asked by At

I'm trying to run my c++ code of which introduction of this new code has brought this memory corruption, can any one help me out what would be causing this. After the delete call I'm facing this issue. I also tried placing the newArgs[SZ] = '\0'; after each strncpy call.

The error says:

HEAP CORRUPTION DETECTED after Normal Block(#274) at 0X00C09600 etc

int main(HINSTANCE hInstance, HINSTANCE hPrevInstance, char* argc, int nShowCmd){

    MyClass *obj;
    char args[] = " hello world";
    int SZ = strlen(args);
    int argsLength = 0;

    if(argc != NULL)
        argsLength=strlen(argc);
    SZ+=argsLength;
    char *newArgs = new char[SZ];
    strncpy(newArgs, "",SZ);

    if(argc != NULL)
        strncpy(newArgs, argc,argsLength);

    StrCat(newArgs,args);

    obj = new MyClass(newArgs);
    delete[] newArgs;

    return 0; 
}
2

There are 2 answers

0
Jonathan Mee On

I can't see your MyClass implementation but I would be willing to bet that It keeps a copy of the pointer passed into it's constructor and that it is also trying to work with that after your delete call.

I'd strongly recommend that you stop newing char*s in C++ and use strings.

4
Werner Henze On

You are retrieving the string length of argc. This is without the trailing null byte:

argsLength=strlen(argc);

Later you are copying argc to your buffer. But you are only copying argsLength characters, which is the string without the trailing null byte. strncpy will then only copy the string content and not add the trailing null byte itself (see man strncpy).

strncpy(newArgs, argc,argsLength);

Immediately after strncpy you are appending another string to your newArgs.

StrCat(newArgs,args);

Depending on the content of newArgs after allocation (which might be random, in debug it probably will be filled with a special pattern) strcat fill not find a trailing null byte in newArgs and will thus read beyond the end of the allocated buffer (until it finds a null byte) and will append your string args there - somewhere in the heap and outside your allocated memory. This is a heap corruption.

Besides:

  1. When allocating the memory you need one byte more for the trailing null byte.
  2. What's the use of strncpy(..., "", SZ)?
  3. Use std::string, not error prone C strings.
  4. You are leaking the allocated MyClass object.
  5. In C++ string literals are const.

I would rewrite your program this way (did not compile and test it):

int main(HINSTANCE hInstance, HINSTANCE hPrevInstance, char* argc, int nShowCmd)
{
    const char args[] = " hello world";
    std::string newArgs;
    if(argc != NULL)
        newArgs = argc;
    newArgs += args;

    // Use the line that you prefer
    MyClass obj1(newArgs.c_str());
    std::unique_ptr<MyClass> obj2(new MyClass(newArgs.c_str()));

    return 0; 
}