sprintf應該都不陌生,不過sprintf()使用上世有風險的,它的原型是: int sprintf(char *str,const char *format,...) 也就是說使用前必須先建立好空間,再用sprintf()將內容填入: int temp=10; char str[20]; sprintf(str," %d * %d *= %d",temp,temp,temp*temp); str輸出來看的結果為:10 * 10 = 100 但如果今天temp為10000,輸出就是: 10000 * 10000 = 100000000 則長度超過20,造成over flow的問題 用snprintf/asprintf取代不安全的sprintf才是最好的 #include <stdio.h> void get_strings(char const *in){ char *cmd; int len = strlen("strings ") + strlen(in) + 1; cmd=(char*)malloc(len); snprintf(cmd, len, "strings %s", in); printf("cmd:%s\n",cmd); free(cmd); } 用snprintf,需要先確定長度,還需要自己調用malloc 使用asprintf,它會自動調用malloc void get_strings_(char const *in){ char *cmd; asprintf(&cmd, "strings %s", in); printf("cmd:%s\n",cmd); free(cmd); } --------------------- asprintf跟sprintf很像,區別在於傳入的是字串的位址而不是字串本身, asprintf()會自動分配空間 int asprintf(char **str,char *fmt,...) _
留言
張貼留言