Sunday, 15 August 2010

C : malloc seems to allocate more then i'm requesting (array) -



C : malloc seems to allocate more then i'm requesting (array) -

hi have question: why when i'm allocating memory malloc float array, allocate more space i'm requesting? illustration in code i'm trying allocate 10 "cells" float array, if seek access other cells returns me no segfault error:

#include <stdio.h> #include <stdlib.h> #include <string.h> float *fk_array; int main(int argc, char** argv){ fk_array = (float *) malloc(10 * sizeof(float)); int i; fk_array[9] = 2.23; fk_array[15] = 0.3; for(i = 0; i<20 ; i++) printf("%f\n",fk_array[i]); free(fk_array); homecoming 1; }

it returns me :

0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 2.230000 0.000000 0.000000 0.000000 0.000000 0.000000 0.300000 0.000000 0.000000 0.000000 0.000000

where i'm in wrong??

when calling malloc, additional space may used store metadata allocated block, such size , info other allocated blocks. implementation prefers allocated blocks @ specific intervals (e.g., multiples of 4 or 8 bytes). however, shouldn't depend on amount of space beingness consistent each time phone call malloc; utilize have requested or may overwriting other of import information.

see answers next questions more information:

how free , malloc work in c? why malloc allocate different number of bytes requested?

c arrays segmentation-fault malloc

No comments:

Post a Comment