简体   繁体   中英

Malloc-Dynamic memory allocation

Code:

int *a;
char *b;
float *c;
short*d;
a = malloc(10* sizeof(int)); 
b = malloc(10 * sizeof(char)); 
c = malloc(16 * sizeof(float));
d = malloc(32 * sizeof(short));
printf("\n a:%d b:%d c:%d d:%d", a, b, c, d);

When i execute the programm, i can understand that each malloc differs from one another some bytes(when allocated in memory). Can anyone explain why this happens? For example the first and second malloc differ 80 bytes. The second and the thrid differ 24 bytes. Why this is happening?

There is no guarantee that multiple malloc 'd objects will be contiguous in memory; depending on how fragmented your heap is, how your heap manager does its internal bookkeeping, whether it uses a "first fit" or "best fit" algorithm, alignment requirements, etc., two successively allocated objects may be nowhere near each other.

The values returned by malloc are unspecified; they depend on the particular malloc implementation.

Some simple implementations use linked list, some more advanced use buckets of various sizes, some round up to the nearest multiple of some size.

So you cannot depend on any particular "difference" between two successive malloc return values. And why would you?

Note first that best practice for mallocing arrays is to multiply the element count by what the pointer points to, ie

a = malloc(10 * sizeof *a); 
b = malloc(10 * sizeof *b); 
c = malloc(16 * sizeof *c);
d = malloc(32 * sizeof *d);

This way you can change the type without touching the malloc arguments.

Note second, the printf format specifier for a pointer is %p and the argument must be cast to (void *) (unless it already is a ptr-to-void).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM