Why runtime error when len >5 in c code


  • 0
    X

    The below is my c code

    int* plusOne(int* digits, int digitsSize, int* returnSize) {

    int* r = (int*)malloc(digitsSize+1);
    
    int m = digits[digitsSize-1]+1;
    r[digitsSize]=m%10;
    int k = m/10;
    
    for(int i=digitsSize-1;i>0;--i){
        m = digits[i-1]+k;
        r[i]=m%10;
        k=m/10;
    }
    
    r[0] = k;
    *returnSize = digitsSize+k;
    return r+1-k;
    

    }

    it works well when len <6, however ,when len>=6, leetcode suggests runtime error. I can run the program with any length on my computer after gcc.


  • 0
    L

    first line int* r = (int*)malloc(digitsSize+1); change to int* r = (int*)malloc(sizeof(int)*(digitsSize+1));


Log in to reply
 

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