переполнение буфера в c6386 при записи - массив указателей - PullRequest
0 голосов
/ 14 января 2020
    Result putInDictionary(Dictionary* d, int key, int value)
{
    //If key is in dictionary, isKeyInDic holds the key's index, if not it holds -1
    int isKeyInDic = isKeyInDictionary(d, key);

    //If key is in dictionary, just repalce it's value and return Sucess
    if (isKeyInDic != -1)
    {
        setVal(d->pairsArray[isKeyInDic], value);
        return SUCEESS;
    }

    //Create a new pair
    Pair* pair = createPair(key, value);

    if (d->size == 0)
    {
        d->pairsArray = malloc(sizeof(Pair*));

        if (d->pairsArray == NULL)
        {
            printf("Malloc failed\n");
            return MEM_ERROR;
        }

        d->size++;
        d->pairsArray[0] = pair;
        return SUCEESS;
    }

    /*Case it's a new key and the dictionary isn't empty, expand the array with realloc
      Declare a backup pointer in case realloc failes
      Try to expand array's size by 1 (size of Element)
    */

    Pair** backup = d->pairsArray;

    d->pairsArray = realloc(d->pairsArray, sizeof(Pair*) * (d->size + 1));

    //Case realloc failed
    if (d->pairsArray == NULL)
    {
        printf("Malloc has failed\n");
        d->pairsArray = backup;
        return MEM_ERROR;
    }

    //Insertion sort - make sure all of the elements entered to the dictionary are sorted
    for (int i = 0; i < d->size; i++)
    {
        //Case an element with a bigger key than the new element's key is found
        if (getKey(d->pairsArray[i]) > key)
        {
            //Promote size with 1
            d->size++;

            //Move all of the elements from the element found 1 to the right
            for (int j = d->size - 1; j > i; j--)
            {
                d->pairsArray[j] = d->pairsArray[j - 1];
            }

            //Insert the new element in the place the bigger element's key is found
            d->pairsArray[i] = pair;

            return SUCEESS;
        }
    }

    /*Case the new element's key is bigger than any of the others
      Promote size with 1
      Insert the new element in the last spot of the array
    */
    d->size++;

    d->pairsArray[d->size - 1] = pair;

    return SUCEESS;
}

У меня есть ошибки в 2 строках:

  1. getKey(d->pairsArray[i])
  2. d->pairsArray[d->size - 1] = pair;

Я не могу понять, Почему. Это структуры:

    struct Pair
{
    int key;
    int val;
};


    struct Dictionary
{
    Pair** pairsArray;
    int size;
};

В нем говорится, что 8 байтов могут быть прочитаны, но я не могу понять, как это возможно. Я знаю, что могу проигнорировать это, но я все еще хочу иметь проверку if, которая в любом случае предотвратит это.

Это ошибка, написанная в строках, которые я написал

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...