I\'m a beginner C programmer, and I assumed that this would be the case, but would like some affirmation if possible.
If they are the same, why not just take one arg
Despite the accepted answer (which I believe to be correct), there seems to be confusions about how many bytes are allocated due to alignment. So here's a little test on my 32-bit Linux with gcc-4.3:
#include
#include
int main()
{
char* p1 = calloc(6, 4);
char* p2 = calloc(4, 6);
char* p3 = calloc(1,1);
printf("%p, %p, %p\n", p1, p2, p3);
return 0;
}
The result is:
0x826b008, 0x826b028, 0x826b048
which shows that both calloc(6,4) and calloc(4,6) allocate the same amount of memory, which is rounded to 32 bytes on my system. Changing the numbers to calloc(3,4) and calloc(4,3) will give the following result:
0x95d2008, 0x95d2018, 0x95d2028
which shows that 16 bytes are reserved when 12 are requested and allocated to the program. In either case, both calloc(a,b) and calloc(b,a) calls have the same effect on the memory usage.
Added by Jonathan Leffler because 300 characters is never going to be enough.
Consider this program, which leaks memory like a veritable sieve, but demonstrates a point:
#include
#include
int main()
{
int i, j, k;
for (i = 1; i < 17; i++)
for (j = 1; j < 9; j++)
for (k = 0; k < 4; k++)
printf("(%2d,%d)%d: %p\n", i, j, k, calloc(i, j));
return(0);
}
On Windows, under Cygwin, this starts by allocating blocks that are 16 bytes apart (actually, the second block is 24 bytes after the first, but thereafter, they are 16 bytes apart). When allocating (2,7), the block addresses start incrementing by 24 bytes; likewise, (3,4) allocates blocks 16 bytes apart, but (3,5) allocates blocks 24 bytes apart. And, for the record, both (4,6) and (6,4) return pointers 32 bytes apart.
This simply demonstrates that there is some overhead associated with an allocation call. If you look at the archetypal implementation of malloc() et al in K&R, you will see that the size of the block is stored ahead of the memory that you're entitled to use. Different implementations do these things differently; those worried about memory trampling will avoid storing control data near where the user can wreak havoc.
When you calloc(4,6), you only have reliable access to 24 bytes of data. Even if your implementation gives you return values that are 32 bytes apart, you may not safely use any more than the 24 bytes you requested. And debugging versions of malloc() will observe if you write out of the bounds you requested.