Originally Posted by
philip79
Is it not quite illegal to dereference an uninitialized pointer or null pointer (the original post does not say). I'm refering to the usage of *data together with the sizeof operator.
You're right that you cannot dereference an uninitialized or null pointer. However, in sizeof(*data), you're not derefencing. It's taking the size of the structure itself, not the pointer. Consider this example:
Code:
#include <stdio.h>
struct databucket
{
int data1, data2, data3, data4, data5;
};
int main()
{
struct databucket *somedata;
somedata = NULL;
printf("sizeof(somedata) = %u\n", sizeof(somedata));
printf("sizeof(*somedata) = %u\n", sizeof(*somedata));
return 0;
}
That will output:
Code:
sizeof(somedata) = 4
sizeof(*somedata) = 20
Where 20 is the size, in bytes, of a "databucket" structure, and 4 is the size, in bytes, of a pointer, on my system.
Do it like this instead:
Code:
data = malloc( i * sizeof( struct database_input ) )
The argument against doing that is that if you ever change data's type, you must also change the associated malloc() statements (and anywhere else you use sizeof()).