Why did my code in c always get Runtime Error. worked well on my computer.


  • 0
    H
    struct Node {
        int value;
        int index;
        struct Node *next;
    };
    
    int *getRes(int num1, int num2) {
        int *res = malloc(2*sizeof(int));
        res[0] = num1;
        res[1] = num2;
        return res;
    }
    
    int hash(int key, int size) {
        return (key * key) % size;
    }
    
    void addNode(struct Node **array, int key, int index, int value) {
        struct Node *n = malloc(sizeof(*n));
        n->index = index;
        n->value = value;
        struct Node *old = array[key];
        if (old == NULL) {
            array[key] = n;
        } else {
            struct Node *tmp = old;
            while (tmp->next != NULL) {
                tmp = tmp->next;
            }
            tmp->next = n;
        }
    }
    
    int hasValue(struct Node **array, int key, int value) {
        struct Node *n = array[key];
        while (n != NULL) {
            if (n->value == value) {
                return n->index;
            }
            n = n->next;
        }
        return -1;
    }
    
    void release(struct Node **array, int size) {
        int i;
        for (i = 0; i < size; i++) {
            struct Node *n = array[i];
            struct Node *tmp = NULL;
            while(n) {
                tmp = n->next;
                free(n);
                n = tmp;
            }
        }
        free(array);
    }
    
    /**
     * Note: The returned array must be malloced, assume caller calls free().
     */
    int* twoSum(int nums[], int numsSize, int target) {
        int size = numsSize * sizeof(struct Node);
        struct Node **array = malloc(size);
        memset(array, 0, size);
        int i;
        int index1, index2;
        for (i = 0; i < numsSize; i++) {
            int value = nums[i];
            int othervalue = target - value;
            int key = hash(value, numsSize);
            int otherkey = hash(othervalue, numsSize);
            int r = hasValue(array, otherkey, othervalue);
            if (r > 0) {
                index1 = r;
                index2 = i + 1;
                goto _res;
            }
            addNode(array, key, i + 1, value);
        }
    
    _res:
        release(array, numsSize);
        return getRes(index1, index2);
    }

  • 0
    H

    When I used malloc in Q2 addTwoNumbers,it happened also.
    My code has been accept finally because I use 'new' instead of 'malloc'
    maybe something is wrong with 'malloc'


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.