0

Background context: I was doing leetcode twoSum and trying to understand one of the solutions. So, I decided to implement the solutions in the code block and use the debugger.

#include <stdio.h>
#include <stdlib.h>
#define SIZE 50000
int hash(int key);
void insert(int *keys, int *values, int key, int value);
int search(int *keys, int *values, int key);
int* twoSum(int* nums, int numsSize, int target, int* returnSize);

int main()
{
    int ar[4]={2,7,11,15};
    int *ans;
    int *returnSize;
    ans=malloc(2*sizeof(int));
    ans=twoSum(ar,4,9,returnSize);
    printf("d d ",ans[0],ans[1]);
    free(ans);
    return 0;
}


int hash(int key) {
    int r = key % SIZE;
    return r < 0 ? r + SIZE : r;
}

void insert(int *keys, int *values, int key, int value) {
    int index = hash(key);
    while (values[index]) {
        index = (index + 1) % SIZE;
    }
    keys[index] = key;
    values[index] = value;
}

int search(int *keys, int *values, int key) {
    int index = hash(key);
    while (values[index]) {
        if (keys[index] == key) {
            return values[index];
        }
        index = (index + 1) % SIZE;
    }
    return 0;
}

int* twoSum(int* nums, int numsSize, int target, int* returnSize){

    *returnSize = 2;
    int keys[SIZE]; //new array
    int values[SIZE] = {0}; //new array
    for (int i = 0; i < numsSize; i++) {
        int complements = target - nums[i];
        // check for complements in the hash table
        int value = search(keys, values, complements);
        if (value) {
            //return an array
            int *indices = (int *) malloc(sizeof(int) * 2);
            indices[0] = value - 1;
            indices[1] = i;
            return indices;
        }
        //if not insert the current values
        insert(keys, values, nums[i], i +1);
    }
    return NULL;
}    
  1. When I use the debugger, the error SEGMENTATION fault appears at line *returnSize=2? What is the problem?

  2. I was trying to understand why i+1 in insert(keys, values, nums[i], i +1) instead of i?

Gerhard
  • 6,850
  • 8
  • 51
  • 81
hihaha99
  • 17
  • 5

1 Answers1

1

You need to initialize returnSize before you can dereference it. You've got UB because you dereference a pointer that is not initialized. But I suspect what you really wanted was to have returnSize as an output parameter, which would look like this:

int main()
{
    int ar[4]={2,7,11,15};
    int *ans;
    int returnSize;
    ans=malloc(2*sizeof(int));
    ans=twoSum(ar,4,9, &returnSize);
    printf("d d ",ans[0],ans[1]);
    free(ans);
    return 0;
}

Note that returnSize in main() is now of type int (not int*). Its address is passed to the function twoSum. The difference is that the pointer passed to the function points to an existing variable.

Hulk
  • 6,399
  • 1
  • 30
  • 52