为什么以下代码返回分段错误?当我注释掉第7行时,seg错误消失了.
int main(void){
char *s;
int ln;
puts("Enter String");
// scanf("%s", s);
gets(s);
ln = strlen(s); // remove this line to end seg fault
char *dyn_s = (char*) malloc (strlen(s)+1); //strlen(s) is used here as well but doesn't change outcome
dyn_s = s;
dyn_s[strlen(s)] = '\0';
puts(dyn_s);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
干杯!
下面是两个定义的函数,用于查找数字列表的最大值.
mx :: (Ord a) => [a] -> a
mx [] = error "Empty list"
mx [x] = x
mx (x:xs)
| x > (mx xs) = x
| otherwise = (mx xs)
mx' (x:xs) = findMax x xs
where
findMax cmx [] = cmx
findMax cmx (x:xs) | x > cmx = findMax x xs
| otherwise = findMax cmx xs
main = do
print $ mx [1..30]
Run Code Online (Sandbox Code Playgroud)
定时上面的代码,首先是mx'(尾递归),然后是mx(非尾递归),我们有以下时序.
Lenovo-IdeaPad-Y510P:/tmp$ time ./t
30
real 0m0.002s
user 0m0.000s
sys 0m0.001s …Run Code Online (Sandbox Code Playgroud)