-1

The following code compiles and runs perfectly:

typedef struct n {
    char value;
    struct n* next;
} node;
void insert_new_node(node** head, char new_value)
{
    node* new_node = malloc(sizeof(node*));
    new_node->value = new_value;
    new_node->next = NULL;

    if(*head == NULL)
    {
        *head = new_node;
    }
    else
    {
        node* current = *head;

        while(current->next != NULL)
        {
            current = current->next;
        }

        current->next = new_node;
    }
}

My question is - notice that I only actually malloc space for a pointer to a struct... Not for the struct itself (ref: node* new_node = malloc(sizeof(node*));). So my question is, where is this struct data actually stored and if it is stored on the heap, how does this work?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
the_endian
  • 2,259
  • 1
  • 24
  • 49

1 Answers1

5

So my question is, where is this struct data actually stored and if it is stored on the heap, how does this work?

It appears to work, accessing invalid memory is undefined behavior (UB). Don't do that.

To elaborate, as you mention, you have allocated memory only by the size of a pointer, however, you are using that pointer to access memory beyond that boundary. The memory location, outside the allocated block, is not allocated to your program, thus that memory is invalid in context of your program, and trying to access the memory is UB.

Based on the individual scenario, it may cause

  • appear to work
  • overwrite some other memory location
  • produce a segmentation fault
  • print the national anthem of your country
  • order pizza and pony using your credit card for the entire team

any or all, in no particular order.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • I appreciate the info here. I have one other question - Do modern operating systems (Windows 10, macOS, etc...) actually allow anything bad to happen from accessing memory like this other than a potential segfault? I hear of how this can lead to random behavior or overwrites like you said but I've never observed any actual bad behavior other than segfaults. I'm not asserting that this is good and I totally understand and I avoid UB wherever I can... But I'm wondering if this is mostly in embedded systems where OSes may not protect memory that such bad things can occur. – the_endian Jun 06 '19 at 04:48