Assuming that a memory address occupies 4 bytes and a char occupies 1 byte:
char** t;
t = mallo开发者_StackOverflowc(5 * sizeof(char*));
int i;
for (i = 0; i < 5; i++)
t[i] = malloc(sizeof(char) * (i+1));
A minimum of around 35 bytes -- but a typical implementation of malloc will have some minimum allocation size it supports, so in reality, you can expect it to use more memory than that (though exactly how much more will vary).
In a typical case, the minimum allocation will be something like 16 or even 32 bytes, in which case most of the sizes you specified above don't really make any difference -- the last 5 allocations will all be of whatever the minimum happens to be. In a typical case, sizes larger than that will be rounded up to the next power of 2 as well.
That would give 32 bytes for your first allocation, and either 16 or 32 (i.e., the minimum supported size) for each of your other five, for a total of either 112 or 192 bytes.
35 bytes (Look below for breakup)
char** t;
t = malloc(5 * sizeof(char*)); // 5 * 4 = 20 bytes
int i;
for (i = 0; i < 5; i++)
t[i] = malloc(sizeof(char) * (i+1)); //1 + 2 + 3 + 4 + 5 = 15 bytes
Let the computer compute for you:
char** t;
t = (char**) malloc(5 * sizeof(char*));
int i;
for (i = 0; i < 5; i++)
t[i] = (char*) malloc(sizeof(char) * (i+1));
unsigned int sz = 5 * sizeof(char*);
for (i = 0; i < 5; i++)
sz += sizeof(char) * (i+1);
printf("%d\n", sz);
35 on a 32 bits machine.
20 for that
t = malloc(5 * sizeof(char*));
15 for that: 5+4+3+2+1
int i;
for (i = 0; i < 5; i++)
t[i] = malloc(sizeof(char) * (i+1));
Get how many bytes are allocated ON YOUR SYSTEM with, for example
#define malloc(s) mm(s)
void *mm(size_t s) {
printf("allocating %d ...\n", (int)s);
return (malloc)(s);
}
/* your code */
Of course, you can sum the sizes instead of printing them.
The malloc()
allocates space rounded up to 16 bytes (at least in win32), so you'll use 32 bytes in the first alloc and 16*5 in the loop.
There is also overhead of malloc (both, time and memory), because malloc()
puts a special header, _CrtMemBlockHeader
before the memory area it returns (that's why you have to give exactly the same pointer to the free()
and are able to use functions like _msize()
.
So, the memory amount actually used would be 32 + 80 = 112 bytes. Considering also the overhead for header: + 5 * sizeof(__CrtMemBlockHeader)
the final amount can be as high as 300 bytes, that is ~8 times larger than the expected 35.
精彩评论