mit23
mit23

Reputation: 53

Why am I getting 8 always?

char *c = (char *)malloc(30*sizeof(char));
printf("%lu \n",sizeof(c));

In the above code I am trying to print the size of 'c'. No matter what number I give instead of '30' in the code, I get the sizeof(c) as 8.

What is the problem? How can I determine the size of an array?

Is length and size the same for an array?

Upvotes: 0

Views: 845

Answers (6)

DieMartin
DieMartin

Reputation: 76

You are printing the size of a char * which in your system is 8.

If you want to know the amount of memory that was "malloc"ed you must store it somewhere. In your case your should store the 30 for future use if you are going to need it.

Upvotes: 3

phuclv
phuclv

Reputation: 41904

You're getting the size of the variable c, not the size of the memory region it points to. There's no way to get the size of an array inside a function because it always decays to pointer. You must store the size yourself. If you've passed the size to malloc then why can't you store that size to a variable?

Upvotes: 0

Eric Fortin
Eric Fortin

Reputation: 7603

At the moment you are asking for the size of a pointer which on a 64 bits machine is 8 bytes. Since this is a malloc and not a real array, you can't retrieve the size of the buffer allocated through c.

If c was declared as

char c[30];

You could determine size with

size_t size = sizeof(c)/sizeof(c[0])

But to be honest if I had to do that, I would just #define the array size even though the size calculation would be stripped out at compilation. It makes the code clearer in my opinion.

Upvotes: 8

Sean
Sean

Reputation: 62502

sizeof(c) means give me the size of the variable c. Since c is a pointer it's giving you back the number of bytes that the pointer takes up in memory. The fact you're seeing 8 suggests you're compiling for 64bit. On a 32bit built it would be 4.

It's your job to remember the size of the thing you've allocated. After all, you asked for an amount of memory, so you do know how much you allocated! In your case, size_t size = 30*sizeof(char) will give you the amount you've allocated.

Upvotes: 1

Henk Kok
Henk Kok

Reputation: 201

Actually sizeof(*c) will return 1. The size of a mallocced buffer cannot be determined compile time (which is what sizeof does).

Upvotes: 0

Eimantas
Eimantas

Reputation: 49354

sizeof is an operator, not a function, thus the compiler creates the code equivalent to something like sizeof(char *) and pointer of a char (depending on the architecture of course) is of 8 bytes.

Upvotes: 0

Related Questions