#include <stdio.h>
char **result = NULL;
int resultSize = 0;
void dfs(char *res, int depth, int n, int left, int right) {
if (depth == n) {
///todo:check res
result[resultSize] = (char *)malloc(depth + 1);
memcpy(result[resultSize], res, depth);
result[resultSize][depth] = '\0';
///printf(">>> pos %d: %s\n", resultSize, result[resultSize]);
resultSize++;
return;
}
if (right > left) {
return;
}
if (left < (n >> 1)) {
res[depth] = '(';
dfs(res, depth + 1, n, left + 1, right);
}
if (right < (n >> 1)) {
res[depth] = ')';
dfs(res, depth + 1, n, left , right + 1);
}
}
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
char ** generateParenthesis(int n, int* returnSize){
char *res = NULL;
*returnSize = 0;
result = (char **)malloc( sizeof(char *) * 1500 );
res = (char *)malloc( sizeof(char) * (n << 1) );
dfs(res, 0, n << 1, 0, 0);
free(res);
*returnSize = resultSize;
return result;
}
int main(int argc, char *argv[])
{
int j = 0;
for (j = 1; j <= 8; ++j ) {
///需要运行多个用例才会出现问题(1 -> 8)
int returnSize;
int i = 0;
char **r = generateParenthesis(atoi(argv[1]), &returnSize);
for (i = 0; i < returnSize; ++i) {
printf(">>> pos %d: %s\n", i, r[i]);
free(r[i]);
}
free(r);
}
return 0;
}
方法:
编译 + 运行::
clang -O -g -fsanitize=address test.c && ./a.out 1
>>> pos 0: ()
AddressSanitizer:DEADLYSIGNAL
=================================================================
==14808==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000000 (pc 0x0000004f64e2 bp 0x7ffce72ac2b0 sp 0x7ffce72ab9e8 T0)
==14808==The signal is caused by a READ memory access.
==14808==Hint: address points to the zero page.
#0 0x4f64e1 (/home/xx/a.out+0x4f64e1)
#1 0x445c85 (/home/xx/a.out+0x445c85)
#2 0x44644b (/home/xx/a.out+0x44644b)
#3 0x44651e (/home/xx/a.out+0x44651e)
#4 0x512452 (/home/xx/a.out+0x512452)
#5 0x7f4a0b8e4bf6 (/lib/x86_64-linux-gnu/libc.so.6+0x21bf6)
#6 0x419d19 (/home/xx/a.out+0x419d19)
AddressSanitizer can not provide additional info.
SUMMARY: AddressSanitizer: SEGV (/home/xx/a.out+0x4f64e1)
==14808==ABORTING
修正:添加 resultSize = 0; 每个测试用例前清零。
char ** generateParenthesis(int n, int* returnSize){
char *res = NULL;
*returnSize = 0;
resultSize = 0;
result = (char **)malloc( sizeof(char *) * 1500 );
res = (char *)malloc( sizeof(char) * (n << 1) );
dfs(res, 0, n << 1, 0, 0);
free(res);
*returnSize = resultSize;
return result;
}