2011年8月30日星期二

segmentation fault with sprintf

Bad way:
int lines = 1234;
char *buffer;
sprintf(buffer, "Lines: %d", lines); // very bad!


Proper way:
int lines = 1234;
char *buffer;
buffer = new char[32];
sprintf(buffer, "Lines: %d", lines);
delete[] buffer;

Alternate proper way, using C allocation semantics way:
int lines = 1234;
char *buffer;
if((buffer = (char *)malloc(32)) != NULL)
sprintf(buffer, "Lines: %d", lines);
free(buffer);

2011年8月24日星期三

preg_replace 去除字符串中间空白

$handy = trim($handy);
$handy = preg_replace("#[^0-9\+]#", "", $handy);