【发布时间】:2021-03-07 14:03:16
【问题描述】:
我正在尝试解决这个问题 “给定一个整数数组 nums 和一个整数目标,返回两个数字的索引,使它们加起来为目标。” 这段代码工作正常,并在我的本地机器上给出了正确的输出,但这在 leet 代码中不起作用。 当我在 leet 代码中运行它时,我收到错误消息:AddressSanitizer heap-use-after-free。 我无法弄清楚我在哪里使用了超出范围的内存。
typedef struct entries
{
int val;
int index;
}entry_t;
typedef struct table
{
entry_t *entry;
}ht_t;
ht_t *table;
int hash(int key, int size)
{
int slot = key % size;
return slot < 0 ? (slot + size) : slot;
}
void insert(int key, int index, ht_t *table, int size)
{
int slot;
slot = hash(key, size);
table->entry[slot].val = key;
table->entry[slot].index = index;
}
int *search(int key, int num, ht_t *table, int size)
{
int slot;
slot = hash(key, size);
if(table->entry[slot].val == key)
{
return &(table->entry[slot].index);
}
return NULL;
}
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
int i;
*returnSize = 2;
int *returnArr= (int*) malloc((2)*sizeof(int));
//int i;
int complement;
int *retVal;
//int size = numsSize;
table = (ht_t *)malloc(sizeof(ht_t)*1);
table->entry = malloc(sizeof(entry_t)*100);
for(i=0; i<numsSize; i++)
{
complement = target - nums[i];
// look for the other number
retVal = (search(complement,nums[i], table, numsSize));
if(retVal != NULL)
{
returnArr[0] = *retVal;
returnArr[1] = i;
break;
}
// if not found insert it to the table.
insert(nums[i],i,table, numsSize);
}
free(table);
free(table->entry);
return returnArr;
}
int main(void) {
//int arr[6] = {1,2,3,8,5,6};
int arr[6] = {2,7,11,15};
int target = 9;
int* indices = malloc(sizeof(int)*2);;
indices = twoSum(arr, 4, target, indices);
printf("index1 = %d, index2 = %d\n",indices[0], indices[1]);
free(indices);
}
【问题讨论】:
标签: arrays c pointers hashtable