logo
down
shadow

singly linked list c++ constructor, destructor and printing out


singly linked list c++ constructor, destructor and printing out

By : Ali Ramzan
Date : November 25 2020, 04:01 AM
I hope this helps . I am a beginner learning c++, and currently making a singly linked list. I have faced some problems and I thought for a very long time, searched a lot but still do not have an answer for this code so I am begging for some help.. , You could cover the issue with a pointer to pointer:
code :
List(T* arr, int n_nodes)
{
    Node<T>** tmp = &head; // tmp *pointing* to uninitialized(!) head pointer
    for(int i = 0; i < n_nodes; i++)
    {
        Node<T>* node = new Node<T>();
        node->data = arr[i];
        // now the trick:
        *tmp = node; // !!!
        // you now have assigned the new node to whatever pointer
        // the tmp pointer points to - which initially is - guess - head...

        // but we now need to advance!
        tmp = &node->next;
    }
    // tmp now points to latestly created node's next pointer
    // (or still head, if no nodes where created because of n_nodes == 0)
    // be aware that this one still is not initialized! so:
    *tmp = nullptr;
}
Node<T>* ptr, tmp;
for(ptr = head->next; ptr == NULL; ptr = head->next)
{
    delete ptr; // you delete ptr, but advancing (ptr = head->next)
                // is done AFTERWARDS, so you'd access already deleted memory
                // undefined behaviour
}
while(head)
{
    Node<T>* tmp = head; // need a copy of pointer
    head = head->next;   // need to advance BEFORE deleting
    delete tmp;          // now can delete safely
}


Share : facebook icon twitter icon
Singly linked list C, printing

Singly linked list C, printing


By : Witek
Date : March 29 2020, 07:55 AM
Any of those help You should format your code properly. first->data is allocated via malloc() and isn't initialized, so using its value invokes undefined behavior. In order not to deal the first element specially, you should use pointer to pointer to have createlist() modify first. Since createlist() won't return anything, type of its return value should be void. I guess you wanted to copy the strings instead of assigning the first character of each strings. To print all of what you entered, code to do so have to be written. You shouldn't use gets(), which has unavoidable risk of buffer overrun. You should free() whatever you allocated via malloc().
improved code:
code :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct Node
{
    char *data;
    struct Node *next;
} node;

void createlist(node **pointer, char data[100])
{
    while (*pointer != NULL)
    {
        pointer = &(*pointer)->next;
    }

    *pointer = malloc(sizeof(node));
    if (*pointer == NULL)
    {
        perror("malloc 1");
        exit(1);
    }
    (*pointer)->data = malloc(strlen(data) + 1);
    if ((*pointer)->data == NULL)
    {
        perror("malloc 2");
        exit(1);
    }
    strcpy((*pointer)->data, data);
    (*pointer)->next = NULL;
}

int main(void)
{
    node *first = NULL;

    printf("Enter the lines\n");
    while (1)
    { 
        char data[100], *lf;
        if (fgets(data, sizeof(data), stdin) == NULL) strcpy(data, "quit");
        if ((lf = strchr(data, '\n')) != NULL) *lf = '\0'; /* remove newline character */
        createlist(&first, data);
        if (strcmp(data, "print") == 0)
        {
            node *elem = first;
            while (elem != NULL)
            {
                printf("%s\n", elem -> data);
                elem = elem->next;
            }
        }
        else if (strcmp(data, "quit") == 0)
        {
            while (first != NULL)
            {
                node *next = first->next;
                free(first->data);
                free(first);
                first = next;
            }
            return(0);
        }

    }

}
Singly Linked List - Segmentation Error due to Destructor implementation

Singly Linked List - Segmentation Error due to Destructor implementation


By : Snir Morlevi
Date : March 29 2020, 07:55 AM
I wish this help you I'm trying to figure out why I'm getting a seg-error from my singly linked list implementation. , You have UB right here:
code :
std::unique_ptr<Node> new_node;
new_node->val = move(a);
std::unique_ptr<Node> new_node = std::make_unique<Node>(); // C++14 or later
std::unique_ptr<Node> new_node( new Node ); // pre C++14
delete &old;
std::unique_ptr<Node> tail ;
What is the proper way to delete a singly-linked-list in destructor?

What is the proper way to delete a singly-linked-list in destructor?


By : keith
Date : March 29 2020, 07:55 AM
may help you .
As you can see if I just use delete next; in destructor then I get it called as many as nodes in the list
Printing a Singly Linked List

Printing a Singly Linked List


By : Jill Rivas
Date : March 29 2020, 07:55 AM
like below fixes the issue What you need is a stack. Your system provides one automatically for you when you call a function recursively:
How is this singly linked list destructor causing an infinite loop?

How is this singly linked list destructor causing an infinite loop?


By : kmcoder
Date : March 29 2020, 07:55 AM
Hope this helps In version 2, you have written a loop that clears up the entire list in one destructor call by looping through the list and deleting every element. However, what happens is not that you have just one destructor call. Every time an element is deleted, that calls the destructor again.
So in the end, the delete follow translates to delete this (because follow = this;) for the first invocation. This then causes the destructor of the first node to be called again, causing the endless loop.
Related Posts Related Posts :
  • C++ on Vistual Studio with CMake error: manifest 'build.ninja' still dirty after 100 tries
  • Is there a way to automatically resolve an overloaded method via a template parameter?
  • Fastest way to find pair in a vector, remove it while iterating
  • error C2440: '=': cannot convert from 'const char *' to 'LPCWSTR'
  • Unable to call boost::clear_vertex while using listS for the vertex and edge lists
  • Decoding binary data from serial port
  • Pattern to Implement an OO interface to a C program written in an imperative style
  • CEPH + Librados++ is not returning consisten results
  • `LoadLibraryExW` triggers exception `0xC0000023` from `NtMapViewOfSection`
  • static_cast to a struct type to access all of its member variable
  • Forward declaration for boost::intrusive_ptr class to reduce compile time
  • How to use priority_queue with a non-static compare method of class instance?
  • Template parameters inside and outside class/struct
  • Determining prime number
  • How to resolve ambiguity between constructors taking std::string and std::vector
  • My program crashes when I try to change private values from an object
  • Unordered_map with custom class as key
  • Strict aliasing rules broken with templates and inheritance
  • C++ Derived Class Override Return Type
  • How to clone class with vector of unique_ptr to base class
  • error: no match for operator
  • std::vector doesnt accept my struct as template
  • selection of people's contours
  • how to fix the (Error using mexOpenCV) on matlab?
  • Is or was there a proposal for c++ to use the context for short enum values?
  • Fair assumptions about std::hash implementations
  • undefined reference to libusb using cyusb
  • Function returns null pointer instead of address
  • C++17 copy elision and object destruction
  • Input multiple strings via operator>> c++
  • Avoiding overflow boost container
  • How to Write a Lambda Wrapping a Function with Optional Return Value
  • Partial specialization with more template parameters
  • How to convert fixed size array to pointer on pointer array
  • Memory leak in const member constructor with tag dispatching
  • C++ function with a generic and optional class
  • Custom QGraphicsItem That Contains Child QGraphicsItems
  • Are There Restrictions on What can be Passed to auto Template Parameters?
  • Rotating line inside rectangle bounds
  • Why do I need dynamic memory allocation if I can just create an array?
  • How can I convert a text file into a form that MPI_Bcast can send?
  • How to get array of all `this` of an instance
  • Using pointers as parameters
  • Automatic type deduction with const_cast is not working
  • Why does std::is_rvalue_reference not do what it is advertised to do?
  • Function Template Specialization with Forward Declared Type
  • template deduction failed in vector
  • Is there a signed `sizeof` alternative in Qt
  • clarification on overloading the -> operator
  • What is __m128d?
  • QtConcurrent: why releaseThread and reserveThread cause deadlock?
  • Function receiving different value than passed
  • Can C++ close a '''fstream''' variable after '''.close()'''?
  • Is it necessary to overload operator in this specific case
  • Comparing an element of a string array with a string
  • how to dereference a pointer of a map of pointers to objects in c++
  • How recursive function control flow change for static variable?
  • SDL 2 blitting BMP File
  • Why does an extremely large value cause this code to repeat infinitely?
  • Function returning different value than what is in function body before return statement
  • shadow
    Privacy Policy - Terms - Contact Us © bighow.org