My C code always gets a runtime error


  • 1
    N

    My C code always gets a runtime error at "[7,3,2], 18", but it works on my machine. I wonder if I misunderstood the description:

    • Return an array of arrays of size *returnSize.
    • The sizes of the arrays are returned as *columnSizes array.
    • Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().

    Is OJ works like the following?

    int i;
    int *columnSizes, returnSize;
    int **res;
    /* call function */
    res = combinationSum(candidates, candidatesSize, target, &columnSizes, &returnSize);
    
    /* check answer */
    ...
    
    /* free space */
    for (i=0; i<returnSize; ++i) free(res[i]);
    free(columnSizes);
    free(res);
    

    In my code, I pass my answer like the following:

    /* at first */
    int **my_res = NULL;
    int *my_columnSizes = NULL;
    int my_returnSize = 0;
    
    /* for each answer[answer_size] I get */
    my_res = realloc(my_res, (my_returnSize+1)*sizeof(int *));
    my_res[my_returnSize] = malloc(answer_size*sizeof(int));
    memcpy(my_res[my_returnSize], answer, answer_size*sizeof(int));
    
    my_columnSizes = realloc(my_columnSizes, (my_returnSize+1)*sizeof(int));
    my_columnSizes[my_returnSize] = answer_size;
    
    ++my_returnSize;
    
    /* at last */
    *returnSize = my_returnSize;
    *columnSizes = my_columnSizes;
    return res;

  • 0
    L

    can you talk about where is wrong? I write the code as you with C and met runtime error.I can't find the reasion


  • 0
    N

    I use a dynamic array to record current result in backtracking. At first I thought an array like "int a[target/(minimum of candidates)]" would be enough, but I forgot that candidates is unsorted! So I wrote "int a[target/candidates[0]]" and got runtime error.


  • 0
    L
    This post is deleted!

  • 0
    N

    I reopen this question, so you can show your code.


Log in to reply
 

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