1
double *p;
p = malloc(sizeof(p));
if (p != NULL)
{
    *p = 5.15;
}

For some reason, p = malloc(sizeof(p));doesn't work. I try to allocate as much memory as p needs. What is wrong with that?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
yemerra
  • 1,352
  • 4
  • 19
  • 44
  • 1
    You want to allocate as much memory as required by what `p` points to. So `malloc(sizeof(*p));` – StoryTeller - Unslander Monica Mar 03 '16 at 08:01
  • "I try to allocate as much memory as `p` needs. " Why on earth do you want to do such a thing? `p` will be expected to be pointing data having type `double` so the size of buffer should be `sizeof(double)` or `sizeof(*p)`. – MikeCAT Mar 03 '16 at 08:01
  • 1
    Actually `p = malloc(sizeof(p));` works, it allocates the size of a pointer. – Déjà vu Mar 03 '16 at 08:07

1 Answers1

4

I try to allocate as much memory as p needs.

p itself (as a variable) has got the (own) memory allocated, what you're trying is basically allocate the memory for which p will be pointing to.

Here, p points to a double, so it needs to have a memory area to be able to store a double value. So, the allocation should be equal to the size of a double, i.e,

p = malloc(sizeof*p);
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261