I was getting realloc(): invalid next size
for a program. So I just coded this to understand what's happening.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *inp;
printf("%lu ",sizeof(inp));
char *res = (char*)malloc(15*sizeof(char*));
printf("%lu ",sizeof(res));
res = "hello world";
printf("%lu\n",sizeof(res));
return 0;
}
And surprisingly it outputs 8 8 8
. Can anyone explain why is it like that? Why is it 8 by default? And how malloc()
effects size of inp
?
You are using sizeof
.returns size in bytes of the object representation of type. Remember sizeof is an operator.
Now sizeof is returning here 8 a constant type of size_t
Why isn't it changing? because in all tha cases you are using the same type that is char *
.
Here 8 bytes is the size of the character pointer that is 64 bit.
You can probably have a look at this-
printf("size of array of 10 int: %d\n" sizeof(int[10]));
This will give the output:40
. 40 bytes.
And malloc
will never affect the size of a char*
. It still needs 64 bits to store an address of a dynamically allocated space from heap.
There is no standard way to do this. You have to take this overhead on your own. You may find some extensions to the compiler that may accomplish this.