LeetCode: fault list
1. malloc memory should always use the following form:
int *a = malloc(sizeof(int) * 3); int **b = malloc(sizeof(int*) * 3); int i = 0; for (; i < 3; i++) { b[i] = malloc(sizeof(int) * 3); } char *c = malloc(sizeof(char) * length); char **pc = malloc(sizeof(char *) * 4); for (i = 0; i < 4; i++) { pc[i] = malloc(sizeof(char) * 3); }
2. memset memory to 0 should use the form:
// Using the malloced memory above: memset(a, 0, sizeof(int) * 3); memset(b, 0, sizeof(int*) * 3); for (i = 0; i < 3; i++) { memset(b[i], 0, sizeof(int) * 3); } memset(c, 0, sizeof(char) * 3); memset(pc, 0, sizeof(char *) * 4); for (i = 0; i < 4; i++) { memset(pc[i], 0, sizeof(char) * 3); }
3. malloc(0) might also return address which is non-null. Which is error-prone. Consider use the following malloc. (..my implementation, any suggestion?)
#define SMALLOC(x) \ ({ \ void *addr; \ if ((x) == 0) \ addr = 0; \ else addr = malloc(x); \ (addr); \ })
4. assign value from variables of different types *NEEDS* explicit type conversion. (e.g. when using double pow(double, double)), because values of different type has different binary presentation.
int ret = 0; ret = (int)pow( (double)2.0, (double)1);
5. when retrieving N's decimal digits, it is better to do as the following, rather than doing: N mod(i*=10), because when N is large enough, i might overflow:
int a[20]; memset(a, 0, sizeof(int)*20); while (N) { a[i++] = N%10; N /= 10; }
6. doing swap using xor should be careful when equals. (when eauals each is set 0)
int swap(int *x, int *y) { if (*x != *y) { *x = *x ^ *y; *y = *x ^ *y; *x = *x ^ *y; } return 0; }