c - What does 'pre'-allocating of a pointer, yet to be used, mean? -
i'm storing unknown-sized info in global unsigned char pointer-variable, doing in function. after having stored data, can tell info size. if so, need reallocate pointer actual pointer size? pointer allocated @ first p = malloc(sizeof(unsigned char)); workability reason. without seg fault, don't understand why necessary.
example:
static void func(); unsigned char *p; int p_size=0; int main() { p = malloc(sizeof(unsigned char)); // why necessary? func(); /* fine - need reallocation of p knowing size p_size ?*/ p = realloc( p , p_size * sizeof(unsigned char)); homecoming 0; } static void func(){ /*if reallocating p , p_size <= 13, heap corruption; "realloc():invalid next size:..." otherwise if not reallocating p no errors , p_size increasable desired*/ for(p_size; p_size <= 12; p_size++) *(p + p_size) = 'a' + p_size; } as stated in comments, code works fine without reallocation of pointer - means, can store many info pointer without need of reallocating memory?
and why heap corruption when reallocating p , setting p_size <= 13 in loop , otherwise not?
what doing dangerous. allocating plenty space single unsigned char 1 byte, , you're writing arbitrary amount of data. it's luck programme doesn't crash every single time. buffer overflow.
you need allocate plenty memory in advance hold info you're going write. if can't predict in advance, need check during func() phone call have plenty room left, , if not reallocate or abort.
c pointers memory-management
No comments:
Post a Comment