Search code examples
cdynamic-memory-allocationsizeofdereferencepointer-to-member

difference between sizeof *ptr and sizeof **ptr when allocating memory


In this piece of code:

void func(size_t dim, double **ptr){
   (*ptr) = malloc(dim * sizeof **ptr);
   /* Perform Calculations...*/
}

What is the difference between using sizeof **ptr and sizeof *ptr? This is confusing me. It seems to have no difference when I'm dealing with int* and double* types, but when I'm dealing with chars*, using sizeof **ptr results in a segmentation fault. Could you help me with that?

Thanks in advance!


Solution

  • What is the difference between using sizeof **ptr and sizeof *ptr?

    sizeof *ptr is the size of the type that ptr points to.

    sizeof **ptr is the size of the type that is pointed to by what ptr points to.

    The declaration double **ptr says ptr is a pointer to a pointer to a double. Then *ptr is a pointer to a double, so sizeof *ptr is the size of a pointer to double. And **ptr is a double, so sizeof **ptr is the size of a double.

    It seems to have no difference when I'm dealing with int* and double* types, but when I'm dealing with chars*, using sizeof **ptr results in a segmentation fault.

    If a pointer is four bytes in your system, an int is four bytes, and a double is eight bytes, then allocating enough space for an int or double also allocates enough space for a pointer. However, allocating space for a char is not enough for a pointer.

    This is actually unlikely to make a noticeable different for a single pointer, as malloc commonly works in units of eight or 16 bytes, so asking it to allocate space for a char would actually give enough for a pointer, notwithstanding compiler optimization. However, if you allocate dim * sizeof **ptr bytes where ptr has type char ** and dim is large, then this will only allocate enough space for dim char elements and not enough space for dim pointers.