0

I`m learning by myself Clang, and started with pointers. To learn a bit I started creating a simple LinkedList program to try to "play" with pointers and addresses.

#include <stdio.h>

struct Node
{
  double value;
  struct Node *nextNode;
};

struct LinkedList
{
  struct Node *initialNode;
};

int
addFirstElement (struct LinkedList *container, struct Node *newElement)
{
  container->initialNode = newElement;
  return 1;
}

int
add (struct LinkedList *container, struct Node *newElement)
{
  struct Node *iterator = container->initialNode;
  int addedCorrectly = 1;
  if (iterator == NULL)
    addedCorrectly = addFirstElement (container, newElement);
  else
    {
      while (iterator->nextNode != NULL)
    iterator = iterator->nextNode;
      iterator->nextNode = newElement;
    }
  return addedCorrectly;

}
/*Esta funcion no genera bien la dirección de memoria, pasa algo raro*/
int
addValue (struct LinkedList *container, double val)
{
  struct Node newElement = {val, NULL};
  return add (container, &newElement);
}

void
printList (struct LinkedList *container)
{
  struct Node *element = container->initialNode;
  printf("HEADER => ");
  while (element != NULL)
    {
      printf ("%f -> ", element->value);
      element = element->nextNode;
    }
    printf("NULL\n");
}

int
main ()
{
  struct LinkedList container = { NULL };
  struct Node val = { 15., NULL };
  struct Node val2 = { -19., NULL };
  struct Node val3 = {29., NULL};
  add(&container, &val);
  add(&container, &val2);
  add(&container, &val3);
  addValue(&container, 29.5);
  printList(&container);
}

Everything went smoothly until i wrote the function addValue, which simply creates a Node structure to add it at the end of the LinkedList struct. The problem appears when i create a new element with this function and try to print the list with printList. I had to debug the code and found something really weird. Right when the function is executed, a new NextNode is created (the new address is 0x7fffffffdda8, with a value of 6.9533558074010171e-310 and creates a new pointer to 0x402e000000000000)

¿What really happens here?

  • 1
    You are never allocating any memory - just adding using the address of local variables which is very wrong. You need to look up malloc and learn a bit more about variable scope. – John3136 Jun 19 '22 at 19:25
  • @John3136 Oh im sorry, i think i understand what u have said but since im new to how CLang works with some things, ¿could u explain it in a more detail way? – Moffinguer Jun 20 '22 at 16:06
  • This is basic stuff any online course or book will cover. Your question is definitely a duplicate - I'll try to fine a good answer. – John3136 Jun 20 '22 at 23:38
  • I believe so, thank you @John3136 – Moffinguer Jun 21 '22 at 08:52

0 Answers0