warning: function returns address of local variable 错误
原因:
函数返回了局部变量(函数中的局部变量存放在stack中,函数执行完成之后会自动释放,因此不应将局部变量的指针作为返回值。)
例:在函数int_to_str()中返回了buf此局部变量。
char* *int_to_str(int value){
char buf[20];
sprintf(buf,"%d",value);
return buf;
}
解决
-
将局部变量声明为static。
char* *int_to_str(int value){ static char buf[20]; sprintf(buf,"%d",value); return buf; }
-
申请变量内存时用malloc():用户malloc申请的内存在堆上,函数结束不会被回收,在使用完此区域后需要free()掉。
char* *int_to_str(int value){ //char buf[20]; char *buf=(char*)malloc(20); sprintf(buf,"%d",value); return buf; }
补:malloc示例
https://blog.csdn.net/qq_26437925/article/details/51654927?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522165138803116781685359449%2522%252C%2522scm%2522%253A%252220140713.130102334…%2522%257D&request_id=165138803116781685359449&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2allsobaiduend~default-1-51654927.142v9control,157v4control&utm_term=malloc%E5%92%8Cfree%E7%9A%84%E7%BB%8F%E5%85%B8%E4%BE%8B%E5%AD%90&spm=1018.2226.3001.4187