Ad

Binary Watch Leetcode - C Indeterminate Solution

- 1 answer

Trying to solve this here puzzle from leetcode. My code sometimes runs fine with no errors, but other times - with the same input - I get this error message:

AddressSanitizer:DEADLYSIGNAL ================================================================= ==33==ERROR: AddressSanitizer: SEGV on unknown address 0x63226afa2260 (pc 0x000000401a05 bp 0x7ffecf0326c0 sp 0x7ffecf0326b0 T0) ==33==The signal is caused by a WRITE memory access. #9 0x7f0b0096982f in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2082f) AddressSanitizer can not provide additional info. ==33==ABORTING

I can't figure out where my code is going wrong. I'm a C newbie so this might be pretty obvious. I went for a backtracking solution using an int called "time" to represent both the minutes and the hours. The first 6 least significant bits are the minutes and the next 4 bits are the hours.

Here's my code:

#define REPRSIZE 6
#define HBITS 4
#define MBITS 6
#define TBITS (MBITS + HBITS)
#define HMAX 12
#define MMAX 60

//assumes valid time: first 6 least significant bits = mins, next 4 bits = hours
char *repr(int mins, int hours){
    char *s = (char*)malloc(REPRSIZE * sizeof(char*));
    sprintf(s, "%d:%02d", hours, mins);
    return s;
}

void addIfValid(char **ans, int *returnSize, int time) {
    int mins = time & 0b111111; //6 bits
    int hours = time >> MBITS;
    if (mins < MMAX && hours < HMAX) {
        ans[(*returnSize)++] = repr(mins, hours); //legal ++?
    }
}

void _readBinWatch(int n, char **ans, int *returnSize, int time, int i) {
    if (!n) {
        addIfValid(ans, returnSize, time);
        return ans;
    } else {
        while (i < TBITS) {
            int mask = 1 << i;
            _readBinWatch(n-1, ans, returnSize, time | mask, ++i);
        }
    }
    return ans;
}

char **readBinaryWatch(int num, int* returnSize) {
    char **ans = malloc(1024 * sizeof(char *));
    _readBinWatch(num, ans, returnSize, 0, 0);
    return ans;
}
Ad

Answer

(Big thanks to MikeCAT for solution)

The returnSize was not initialized. All I had to do was add *returnSize = 0;!

Ad
source: stackoverflow.com
Ad