Search code examples
cmemory-managementbuffer-overflow

C code works on local device but doesn't work on leetcode


I'm trying to solve this leetcode problem

My solution works well on my own computer, but gives an error when I try to run it on leetcode

The error I get is this:

==31==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x602000000033 at pc 0x55679c033f3b bp 0x7ffe5ea0aca0 sp 0x7ffe5ea0ac90

When I allocate a fixed value to the string variable in the convert function instead of string_len, the error is resolved. how can I solve this problem?

excuse me for my bad English.

this is my code:

#include <stdio.h>
#include <stdlib.h>

int find(int item, int* array) {
    int index;
    for (index = 0; array[index] != item; index++);
    return index;
}

int pow2ten(int number, int time) {
    for (int count = 0; count < time; count++)
        number = number * 10;

    return number;
}

int count_len(int number) {
    int count = 1;

    for (number = number/10; number; number = number/10)
        count++;
    return count;
}

int compare(int number_1, int number_2)
{
    int len_1 = count_len(number_1);
    int len_2 = count_len(number_2);

    number_1 = pow2ten(number_1, len_2 - len_1);
    number_2 = pow2ten(number_2, len_1 - len_2);

    return number_2 > number_1;
}

char* convert(int number) {
    int string_len = count_len(number);
    char* string = malloc(string_len);
    for (int index = string_len; number; number = number / 10)
        string[--index] = (number%10) + '0';
    return string;
}

char* largestNumber(int nums[], int numsSize) {
       int number, number_len;
       number = number_len = 0;

       for (int count = 0; count < numsSize; count++)
           number_len = number_len + count_len(nums[count]);

       int part_len = 0;
       for (int time = 0; time < number_len; time = time + part_len) {
           int part = 0;

           for (int count = 0; count < numsSize; count++)
               if (compare(part, nums[count]))
                   part = nums[count];
           part_len = count_len(part);
           nums[find(part, nums)] = 0;
           part = pow2ten(part, number_len - time - part_len);

           number = number + part;
       }

       return convert(number);
}

Solution

  • In 'convert' you allocate the memory for a string for the exact length of the string. A C String is terminated by a 0-byte so you have to allocate this extra bayte and initialize it to 0.

    char* string = malloc(string_len+1);
    string[string_len] = 0;
    

    This way the string is now a proper C string after the function exits and find()will not exceed the buffer.