c - c6386 写入时缓冲区溢出 - 指针数组
问题描述
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;
}
我有两行错误:
getKey(d->pairsArray[i])
d->pairsArray[d->size - 1] = pair;
我似乎无法理解为什么。这些是结构:
struct Pair
{
int key;
int val;
};
struct Dictionary
{
Pair** pairsArray;
int size;
};
它说可能会读取 8 个字节,但我不明白这怎么可能。我知道我可以忽略它,但我仍然想要一个 if 检查来阻止它。
解决方案
推荐阅读
- java - 我们如何打印数据集以登录生产级 JAVA-spark 应用程序?我知道 df.show() 打印到控制台。我们如何在日志中打印它?
- django - Django 管理表单为具有条件 UniqueConstraint 的模型引发 IntegrityError
- python - Python Selenium WebDriverWait 不起作用,但 find_element_by_name 起作用
- c++ - LVM_SORTITEMS:取消
- excel - 在运行循环运行良好时收到运行时错误 fefor 不知道为什么现在出错
- azure-devops - 如何在 pytest 中为 Azure DevOps 添加优先级?
- javascript - 如何使用 react-native-fs 递归读取文件系统
- ios - SwiftUI 文本和带参数的 LocalizedStringKey
- bash - 遍历列并仅保留(打印)所有值匹配的列 - AWK
- javascript - 删除对象数组重复项并将非重复值存储在数组中