Search code examples
cmallocunhandled-exception

C - Write access violation


I have an error at the last line, in nullString, a function setting all the string to '\0' with a simple for()

void function ( unsigned char inputArray[], size_t inputSize )
{
    size_t cellSize;
    if (inputSize <= 256)
        cellSize = 1;
    else
        cellSize = ceil(inputSize / 2 / 256) + 1;


    // Sub Box
    unsigned char subBox[255];
    for (size_t line = 0; line < 255; line++)
        subBox[line] = 0;

    generate_SubBox(subBox, key);
    // Sub Box


    // Sub Box reverse
    unsigned char subBox_Inverse[255];
    for (size_t line = 0; line < 255; line++)
        subBox_Inverse[line] = 0;

    generate_SubBox_Inverse(subBox_Inverse, subBox, key);
    // Sub Box reverse        

    unsigned char* inputArray2 = NULL;
    inputArray2 = malloc(sizeof(unsigned char)* inputSize / 2);
    verifyMalloc(inputArray2);
    nullString(inputArray2, inputSize / 2);

    unsigned char string_temp[3] = { 0 };
    size_t w = 0;
    for (size_t i = 0; i < inputSize / 2; i++)
    {
        string_temp[0] = inputArray[w];
        string_temp[1] = inputArray[w + 1];

        inputArray2[i] = strtoll(string_temp, NULL, 16);

        w += 2;
    }
}

I tried neutralizing line per line all instructions coming before nullString() by commenting them but it doesn't change anything.

If I neutralize nullString, the error comes after, at

inputArray2[i] = strtoll(...)

Hope you've got the answer :)

Thanks in advance !

EDIT: Here is nullString:

void nullString(unsigned char input[], size_t length)
{
    for (size_t x = 0; x < length; x++)
        input[x] = '\0';
}

I commented all the instructions before nullString, the error is still there.

I also verified variables and they all look like good

EDIT 2: verifyMalloc:

void verifyMalloc(int* pointer)
{
    if (pointer == NULL)
    {
        perror("Erreur");

        Sleep(15000);
        exit(0);
    }
}

Solution

  • Everything we're seeing is seriously hinting at you forgetting to #include <stdlib.h> (and ignoring the warnings resulting from that).

    This is what might happens when you use malloc() without including stdlib.h in the same file:

    • the compiler consider the malloc() function to be declared implicitly, which means it is assuming that its return type is int (instead of *void).
    • This might work when sizeof (int) is the same as sizeof (*void). But when int is 32-bits while pointers are 64-bits then the address returned by malloc() might lose half of its bits and point to an invalid address.