tomole
tomole

Reputation: 1006

Multiple linked pointers

For a homework I have to build the following simple scenario.

enter image description here

My attempt looks like:

#include <stdlib.h>

int main() {
  char* heap1P = malloc(sizeof(char**));
  char* heap2P = malloc(sizeof(char*));
  char* heap3P = malloc(sizeof(char));

  *heap3P = 'X';
  *heap2P = heap3P;
  *heap1P = heap2P;

  char*** stackP = heap1P;

  puts("stack                           | heap ");
  printf("%p [%p] | %p [%p] => %p [%p] => %c [%p] \n", stackP, &stackP, *heap1P, heap1P, *heap2P, heap2P, *heap3P, heap3P);

  return EXIT_SUCCESS;
}

First I allocate space in memory and after that I set the values. The output is like (format: value [address]):

stack                           | heap 
0x55a1e184f260 [0x7fff05e55c08] | 0xffffff80 [0x55a1e184f260] => 0xffffffa0 [0x55a1e184f280] => X [0x55a1e184f2a0] 

As you can see the stack value contains the address of the first heap value. But the heap values are not correct. They do not contain the address of the following heap value.

Why the heap values do not contain the given addresses?

Upvotes: 1

Views: 73

Answers (2)

Serge Ballesta
Serge Ballesta

Reputation: 148910

The problem is only that you have declared the various pointer as char *. It may look unimportant, because in common implementations all pointers have same representation. But it becomes essential as soon as you dereference them!

Let us look at the following statements:

*heap3P = 'X';
*heap2P = heap3P;

First one is correct: heap3P is a char * and *heap3P is assigned a char, all is fine here.

Second one is terrible. As heap2P is a char *, heap3P if converted to an integer and trimmed into a char! Long story short: you only store one byte from the pointer... And if you look carefully to the values, you will see that the different heapx are indeed single byte values...

The fix is trivial:

char*** heap1P = malloc(sizeof(char**));
char** heap2P = malloc(sizeof(char*));
char* heap3P = malloc(sizeof(char));

and the code compiles without a warning and runs as expected!

Upvotes: 5

Noxet
Noxet

Reputation: 270

I think you would want something like:

typedef struct heap {
    char val;
    struct heap *next;
} heap_t;

int main()
{
    // allocate first
    heap_t *head = malloc(sizeof(heap_t));
    head->val = 'A';
    // allocate second node
    head->next = malloc(sizeof(heap_t));
    head->next->val = 'B';

    head->next->next = malloc(sizeof(heap_t));
    head->next->next->val = 'X';

    heap_t *tmp = head;
    for (int i = 0; i < 3; i++, tmp = tmp->next) {
        printf("[%p, %c]\n", tmp, tmp->val);
    }
}

Note that this is a quick draft, and you should of course do the creation of new nodes inside a function, not the manual way I did here. Do not forget to free the memory afterwards.

Upvotes: 0

Related Questions