写入时c6386缓冲区溢出-指针数组

时间:2020-01-14 20:32:45

标签: c buffer-overrun

    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;
}

我有两行错误:

  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检查,以防止它出现。

Those are the error given to the lines I wrote

0 个答案:

没有答案