当前位置: 技术问答>linux和unix
这个小程序有BUG,请高手指出。。。
来源: 互联网 发布时间:2016-01-28
本文导语: #include #include void foo(int age,char *b){ b = (char *)malloc(64); sprintf(b, "Your age is %d", age); } int main(){ char *f; foo(23, f); printf("%sn",f); } 程序很小,但是有一个bug,不知道在哪里。 | 最...
#include
#include
void foo(int age,char *b){
b = (char *)malloc(64);
sprintf(b, "Your age is %d", age);
}
int main(){
char *f;
foo(23, f);
printf("%sn",f);
}
程序很小,但是有一个bug,不知道在哪里。
#include
void foo(int age,char *b){
b = (char *)malloc(64);
sprintf(b, "Your age is %d", age);
}
int main(){
char *f;
foo(23, f);
printf("%sn",f);
}
程序很小,但是有一个bug,不知道在哪里。
|
最简单的改法
#include
#include
void foo(int age,char **b){
*b = (char *)malloc(64);
sprintf(*b, "Your age is %d", age);
}
int main(){
char *f;
foo(23, &f);
printf("%sn",f);
free(f);
}
面目全非的改法
#include
void foo(int age,char *s, int size){
snprintf(s, size, "Your age is %d", age);
}
int main(){
char s[1024];
foo(23, s, sizeof(s)/sizeof(s[0]));
printf("%sn",s);
}
#include
#include
void foo(int age,char **b){
*b = (char *)malloc(64);
sprintf(*b, "Your age is %d", age);
}
int main(){
char *f;
foo(23, &f);
printf("%sn",f);
free(f);
}
面目全非的改法
#include
void foo(int age,char *s, int size){
snprintf(s, size, "Your age is %d", age);
}
int main(){
char s[1024];
foo(23, s, sizeof(s)/sizeof(s[0]));
printf("%sn",s);
}