Home > OS >  Signed integer overflow
Signed integer overflow

Time:11-06

Below in source code (I've commented the error on code), I get

Line 27: Char 33: runtime error: signed integer overflow: -1094795586 -1094795586 cannot be represented in type 'int'

I've consulted different articles, like How to detected signed integer overflow but I'm not getting which integer to check.
Elements of working_array[] are filtered from nums[] if their value is less than target integer.
Since the elements of nums[] are like [ 3, 6, 11, 19, 2, ...] I'm not worried to checking for overflow during SUM on the last if statement. I'm wrong?

int* twoSum(int* nums, int numsSize, int target, int* returnSize){
    int count_elem = 0;
    int *working_array = (int*)malloc(numsSize * sizeof(int));
    
    // Going through original array
    for(int i=0;i<numsSize;i  ){
        
        // If elem nums[i] is less than target, is accepted on a new working array
        if(nums[i] < target){
            count_elem  = 1;
            working_array[count_elem] = nums[i];            
        }        
    }

    working_array = realloc(working_array, count_elem*sizeof(int));
    
    // Creating result array
    returnSize = sizeof(int)*2;
    int *result_array = (int*)malloc(returnSize);

    // Going through working array
    for(int i=0;i<count_elem;  i)
        for(int j=0;j<count_elem;  j)

            // SIGNED INTEGER OVERFLOW IN LINE BELOW
            if( (working_array[i] working_array[j]) == target){
                result_array[0] = working_array[i];
                result_array[1] = working_array[j];
                free(working_array);
                return result_array;
            }
    
    free(working_array);
    return;
}

P.S: I know that cast malloc results is useless, but this is a minor issue maybe.

CodePudding user response:

        if(nums[i] < target){
            count_elem  = 1;
            working_array[count_elem] = nums[i];     
        }

Off-by-one error. This initializes working_array[1], working_array[2], ... potentially up to working_array[numsSize] which would be out of bounds. Meanwhile, working_array[0] is never initialized and contains garbage, which is probably the garbage value that provokes your overflow.

Make it:

        if(nums[i] < target){
            working_array[count_elem] = nums[i];     
            count_elem  = 1;
        }

or perhaps

        if(nums[i] < target){
            working_array[count_elem  ] = nums[i];     
        }

Also, as noted above,

    returnSize = sizeof(int)*2;
    int *result_array = (int*)malloc(returnSize);

is wrong because returnSize is a pointer. If the idea is to return the size by reference, then you want

    *returnSize = sizeof(int)*2;
    int *result_array = (int*)malloc(*returnSize);
  • Related