cmallocaccess-violation

Access violation after malloc


Could someone please help me understand the following behaviour:

I have a little piece of code for cloning a float image. The method Clone takes a pointer to another image and its dimensions as arguments.

Everything works as expected, but sometimes this line clone[i] = color; causes an Access Violation. The occurrence of the exception is not predictable neither periodic. Inspecting variables at crash time shows that Color color = source[i]; is always set and valid.

How is it possible that malloc returns a bad pointer?

The code:

typedef struct
{
    float r;
    float g;
    float b;
    float a;
} Color;

Color* Clone(Color* source, int width, int height)
{
    int s = width * height;

    Color *clone;
    clone = (Color *)malloc(s * sizeof(Color));

    if (clone)
    {
        for (int i = 0; i < s; i++)
        {
            Color color = source[i];

            // Sometimes app crash here: Access violation
            clone[i] = color;
        }
    }

    return clone;
}

Any help is much appreciated.

Update:

Platform: Windows 64bit

Values of variables at crash time:

width = 256
height = 256
s = 655536
i = 0

Solution

  • I can see nothing terribly wrong with this code. However malloc can indeed return garbage if the heap has been corrupted before. Actually quite often malloc is when one detects that something went wrong and you get an explicit "heap corruption" error message.

    My suggestion is, if possible, to run the program under valgrind in the hope to catch the real bad guy that corrupts heap data structures... something that happens BEFORE calling this cloning function.