Reputation: 2131
My goal is to read a file and store it's contents in a char array given the offset and number of bytes to be read. I have written a function for doing the same and it works fine.
Now this function is to be called from somewhere else. So I am trying to declare a variable char * data
which will hold the contents returned by the above mentioned function. After declaring I tried to allocate it some memory. (I know how much, as I specify the number of bytes to be read). It goes as follows:
char * data;
char * filename = "alphabet.txt";
int data_size = 10;
printf("data size: %d\n", data_size);
data = (char*) malloc (data_size);
printf("Size allocated to data: %d\n",sizeof(data));
return 0;
This code gives the following output:
data size: 10
Size allocated to data: 8
I don't understand this behavior. Can somebody please explain it to me.
Thanks a lot
shahensha
Upvotes: 0
Views: 1178
Reputation: 320401
Apparently you made some completely unfounded assumptions about the behavior of sizeof
. Apparently you assumed that sizeof
can be used to query the size of malloc
-ed memory block.
It can't be. sizeof
has absolutely nothing to do with that. In fact, C library does not provide you with any means to determine the size of malloc
-ed memory block. It is simply impossible. If you want to know how much memory you allocated, you have to devise your own way to remember how much memory you requested from malloc
. End of a story.
sizeof
evaluates to the size of its operand. In this case you supplied a pointer as its operand, so it evaluated to the size of a pointer, which happens to be 8
on your platform.
Upvotes: 0
Reputation: 20383
Just these two lines of code
char * data;
printf("Size allocated to data: %d\n",sizeof(data));
would print (in OP's machine):
Size allocated to data: 8
sizeof
returns the size of the argument, here data
pointer. It is done at compile time.
malloc
has nothing to do with sizeof(data)
.
Upvotes: 0
Reputation: 2853
sizeof
char *ptr
will give the sizeof the pointer address ptr
pointing . Its vary depends on the machine.
char *ptr = malloc(10); malloc will allocate the 10 space and ptr pointing
to the starting address.
Examine below code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char * data;
int data_size = 10;
printf("data size: %d\n", data_size);
data = malloc ((data_size+1)*sizeof(char));
strcpy(data, "datadatada");
printf("string lenght: %d\n",strlen(data));
printf("Size allocated to data: %zd\n",sizeof(data));
return 0;
}
Upvotes: 0
Reputation: 124642
This has nothing to do with malloc
.
sizeof
does its thing at compile time, not runtime. sizeof(data)
is the same as sizeof(char*)
. Your program cannot know at compile time how much memory that pointer refers to.
On the other hand, sizeof(some_array)
would work as you expect because array sizes are known at compile time.
Upvotes: 4