c - Why can't I use malloc to set array size larger than what is needed? -
i coming python using malloc new me. intuitively below should work having syntax issues. in first line want set array size max of 8 ints. in second line, want add 4 ints. line example only, in production have user input 8-digit number. when go compile (clang) size of array has non-integer type 'void *'
if comment out first line , initialize second line (and adding int type) code works. setting size incorrectly. ideas?
int main(void) { int mult_digits[malloc(8 * sizeof(int))]; mult_digits[] = {1,2,3,4}; int size_mult = sizeof mult_digits / sizeof *mult_digits; printf("size of array %d\n", size_mult); return 0; }
this code wrong. call malloc
allocate memory, , malloc
returns pointer. rather deconstructing syntax, broken, i'll give couple of variants of program.
int main(void) { int mult_digits[] = {1,2,3,4}; int size_mult = sizeof mult_digits / sizeof *mult_digits; printf("size of array %d\n", size_mult); return 0; }
here array not allocated dynamically. it's local variable automatic, stored on stack.
for dynamic allocation this:
int main(void) { int *mult_digits = malloc(4*sizeof *mult_digits); mult_digits[0] = 1; mult_digits[1] = 2; mult_digits[2] = 3; mult_digits[3] = 4; free(mult_digits); return 0; }
the argument malloc
number of bytes returned. value returned address of new block of memory. note here made call free
deallocate memory. if omit that, memory leaked.
with variant, there no way recover length of array mult_digits
. know might freak out, coming python, repeat. there no way recover length of array mult_digits
. it's job keep track of information.
now, wanted over-allocate memory. can that:
int main(void) { int *mult_digits = malloc(8*sizeof *mult_digits); mult_digits[0] = 1; mult_digits[1] = 2; mult_digits[2] = 3; mult_digits[3] = 4; free(mult_digits); return 0; }
here used first 4 elements, , ignored final 4. that's fine. in case over-allocate typically need keep track of both allocated length, , in-use length. can add new items increasing in-use length, until reach allocated length. need reallocate larger block. guess that's driving at.
Comments
Post a Comment