Using sizeof() on malloc'd memory [duplicate]
Because the size of the "string" pointer is 8 bytes. Here are some examples of using sizeof()
with their appropriate "size". The term size_of()
is sometimes deceiving for people not used to using it. In your case, the size of the pointer is 8 bytes.. below is a representation on a typical 32-bit system.
sizeof (char) = 1
sizeof (double) = 8
sizeof (float) = 4
sizeof (int) = 4
sizeof (long) = 4
sizeof (long long) = 8
sizeof (short) = 2
sizeof (void *) = 4
sizeof (clock_t) = 4
sizeof (pid_t) = 4
sizeof (size_t) = 4
sizeof (ssize_t) = 4
sizeof (time_t) = 4
Source
You are leaving out how you are determining your string is disappearing (char array). It is probably being passed to a function, which you need to pass the explicit length as a variable or track it somewhere. Using sizeof()
won't tell you this.
See my previous question about this and you'll see even my lack of initial understanding.
In C89, sizeof
operator only finds the size of a variable in bytes at compile time (in this case a void
pointer of 8 bytes). It works the way you'd expect it to work on plain arrays, because their size is known at compile time.
char arr[100]; // sizeof arr == 100
char *p = arr; // sizeof p == 4 (or 8 on 64-bit architectures)
char *p = malloc(100); // sizeof p == 4 (or 8). Still!
To know the size of heap-allocated memory, you need to keep track of it manually, sizeof
won't help you.
sizeof
returns the size of the pointer (void *
) that you gave it, not the size of the memory you allocated. You would have to store the size of the memory in a separate variable if you want to use it later.