这个小程序有BUG,请高手指出。。。
#include <stdio.h>
#include <stdlib.h>
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( "%s\n ",f);
}
程序很小,但是有一个bug,不知道在哪里。
------解决方案--------------------最简单的改法
#include <stdio.h>
#include <stdlib.h>
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( "%s\n ",f);
free(f);
}
面目全非的改法
#include <stdio.h>
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( "%s\n ",s);
}