Wednesday, 15 September 2010

c - realloc() an incremented pointer -



c - realloc() an incremented pointer -

platform: linux 3.2.0 x86 (debian wheezy) compiler: gcc 4.7.2 (debian 4.7.2-5)

i wondering happen if effort realloc() pointer has been incremented. illustration

char *ptr = null; size_t siz = 256; ptr = malloc(siz); ptr = realloc(ptr + 5, siz * 2);

what homecoming value of realloc() phone call be? know realloc()'s documentation states pointer passed must have been returned malloc(), calloc(), or realloc(). assuming means cannot realloc() incremented pointer have been unable verify assumption.

that wouldn't work predictable way, results undefined. 1st argument pass realloc or free must returned malloc, realloc or calloc, or must null.

in case not true ptr[5], because ptr[5] uninitialized. compile error or warning, because ptr[5] not pointer. if pointer (e.g. char **ptr;), still uninitialized, status false, , results undefined, , process crash.

in case not true ptr + 5 either, because ptr + 5 not returned malloc, realloc or calloc (but ptr was), , it's not null. behavior undefined in case, process crash.

c malloc

No comments:

Post a Comment