我在下面的while
循环中获取segmentation fault
。
int main() {
register char *str = "Hello World";
char *ans;
ans = test(str);
if(!ans)
return 1;
free(ans);
return 0;
}
char *test(char *str) {
char *str1 ;
char *str2;
char *str3;
str1 = malloc(strlen(str) + 5);
str2 = str;
str3 = str1;
*str3++ = '\b';
*str3++ = '\b';
while(*str2)
*str3++ = *str2++;
*str3++ = '\f';
*str3++ = '\f';
*str3 = '\0';
return (str1);
}
我想我在while
循环中得到了segmentation fault
。你能告诉我为什么吗?我将其称为char *ans = test(string)
,其中string
是register char *string
。比方说,字符串中有hello world
。我的目的是从test()
返回\b\bHello World\f\f
。
发布于 2016-08-10 15:00:29
您的问题是没有正确地声明函数test
。您必须在使用之前声明所使用的每个函数,无论是通过将实际函数放在上面还是编写函数声明。
一旦你这样做了,你的代码就可以工作了:
#include <stdio.h>
char *test (char *str); // this is the function declaration
int main(void) {
register char *str = "Hello World";
char *ans;
ans = test(str);
if(!ans)
return 1;
free(ans);
return 0;
}
char *test(char *str) {
char *str1 ;
char *str2;
char *str3;
str1 = malloc(strlen(str) + 5);
str2 = str;
str3 = str1;
*str3++ = '\b';
*str3++ = '\b';
while(*str2)
*str3++ = *str2++;
*str3++ = '\f';
*str3++ = '\f';
*str3 = '\0';
return (str1);
}
https://stackoverflow.com/questions/38864558
复制相似问题