realloc()の正しい使い方
a)正しくない使い方
char* buf;
buf = (char*)malloc(1024 * sizeof(char));
if(buf == NULL){
return -1;
}
buf = (char*)realloc(buf, 2048 * sizeof(char));
if(buf == NULL){
/* bufが解放されない */
return -1;
}
b)正しい使い方
char* tmp;
char* buf;
buf = (char*)malloc(1024 * sizeof(char));
if(buf == NULL){
return -1;
}
tmp = (char*)realloc(buf, 2048 * sizeof(char));
if(tmp == NULL){
/* bufを解放 */
free(buf);
return -1;
}
buf = tmp;
確保する領域のポインタと、エラー判定するための戻り値のポインタが同じだとmallocした領域が解放できない。
最近はメモリが潤沢にあるせいかmalloc()、realloc()のエラー判定自体してないソースもよく見かける。