logo
down
shadow

Memory Leak - Singly linked list in C


Memory Leak - Singly linked list in C

By : Kasi
Date : October 23 2020, 06:10 PM
Any of those help I implement this simple code for implement a Singly linked list in C. I just post another question for this code (link). I put the code the same so that you can see it without having to change pages. This is the code: , Careful here:
code :
while ( key_list != NULL ) {
    current = key_list; // current is now a copy of key_list (a copy of the pointer)
    free(current->key);
    free(current);      // here you free current and hence key_list

    key_list = key_list->next; // here you are referring to key_list, just freed above
  }
while ( key_list != NULL ) {
    current = key_list; 
    key_list = key_list->next; 
    free(current->key);
    free(current);      
  }


Share : facebook icon twitter icon
Segmentation Fault when freeing singly linked list from memory

Segmentation Fault when freeing singly linked list from memory


By : Evangelos Vazaios
Date : March 29 2020, 07:55 AM
Does that help Freenode sets the pointer passed to it to NULL. Afterwards freelist tries to dereference the pointer which is now null. That's where the program crashes.
Besides that, your program doesn't really free any data. It just changes the pointers pointing to the data to point to NULL. That means the memory will stay allocated and isn't available for new data. To mark the memory a pointer points to as no longer needed, you need to call the free() method from the standard library on the pointer which points to it. Setting the pointer to NULL afterwards is not needed, but a good practice to make sure that any subsequent try to access the free'ed memory location results in a predictable crash and not in totally unpredictable behavior.
Shuffling a singly linked list using up to log N extra memory and N log N time

Shuffling a singly linked list using up to log N extra memory and N log N time


By : user2671008
Date : March 29 2020, 07:55 AM
around this issue Your problem is that you are emptying the list when you print it in your main method, prior to calling shuffle(l).
You are assigning the list l to a variable called copy, but this variable doesn't contain a copy of the list. It refers to the same list. When you call copy.pop(), you remove an element from the original list. Therefore you call shuffle on an empty list.
code :
public static void main (String[] args)
{
    LinkedList<String> l = new LinkedList<String>();
    LinkedList<String> copy = new LinkedList<String>();
    l.push("A"); l.push("B"); l.push("C"); l.push("D");
    l.push("E"); l.push("F"); l.push("G"); l.push("H");
    copy = l;

    while (copy.size() != 0) StdOut.println(copy.pop()+"  "); // remove this line
                                                              // and your method will
                                                              // work
    shuffle(l);
    while (l.size() != 0) StdOut.println(l.pop()+"  ");
}
public static void shuffle(LinkedList l)
{
    if (l.size() <= 1) return; // instead of == 1
    ...
C malloc valgrind - uninitialised memory in my singly linked list implementation

C malloc valgrind - uninitialised memory in my singly linked list implementation


By : Zhu Liu
Date : March 29 2020, 07:55 AM
Hope this helps You have a few problems. You are checking new_node->next (uninitialized data in malloc'd memory) instead of new_node (the return value of malloc). On my computer at least this also causes memory not to be freed because by chance new_node->next is null so you return without freeing new_node. Also, if you want to support pushing to the back of a linked list, you should consider a circularly linked list because it allows that operation without having to traverse the whole thing.
Finally, a few tips: it's good that you are using valgrind, but it will be more helpful if you compile with -g to enable debugging symbols so valgrind will tell you line numbers. Also, when I make linked lists, I like to use a dummy head node for some operations to avoid a special case for empty or singleton lists. For inserting into a sorted linked list, that technique looks like:
code :
int sorted_insert(Clist *list, char new_command){
    Cnode _head = {NULL, list->head}, *head = &_head, *prev = head, *tmp;//head is an auto dummy node obviating null checks.
    int ord = -1;//If there are no existing nodes, newObj would be less than all objects.
    while(prev->next && (ord = (int)newObj - prev->next->command)) > 0){//Iterate by prev->next not curr to use only one pointer.
        prev = prev->next;//Looping while there is a next node and its data compares less than new_command.
    }
    if((!ord) || !(tmp = malloc(sizeof(Cnode))){//newObj is already in the list or allocation failed.
        return 0;
    }
    *tmp = (Cnode){.next=prev->next, .command=new_command};
    prev->next = tmp;
    list->head = head->next;//un- add head which is then deallocated by stack frame cleanup.
    return 1;
}
How can I return the odd indexed nodes of a singly linked list in a new singly linked list ?Assume index of the first no

How can I return the odd indexed nodes of a singly linked list in a new singly linked list ?Assume index of the first no


By : user3675293
Date : March 29 2020, 07:55 AM
it fixes the issue When I run this code I am not getting an error message from the compiler but I can not return the new list. Am I writing down the code wrong in the MAIN part? , You are always changing the same object pList->next.
code :
       else
       {
           pList->next=pTemp;
       }
#include <stdio.h>
#include <stdlib.h>

typedef struct SinglyLinkedListItem
{
    int data;
    struct SinglyLinkedListItem *next;
} SLLI;

SLLI * OddNodes( SLLI **pHead )
{
    int odd = 0;
    SLLI *pList = NULL;
    SLLI **pCurrent = &pList;

    while ( *pHead != NULL )
    {
        if ( odd ^= 1 )
        {
            *pCurrent = *pHead;
            *pHead = ( *pHead )->next;
            ( *pCurrent )->next = NULL;
            pCurrent = &( *pCurrent )->next;
        }
        else
        {
            pHead = &( *pHead )->next;
        }
    }

    return pList;
 }

 int insert( SLLI **pHead, int data )
 {
    SLLI *pCurrent = malloc( sizeof( SLLI ) );
    int success = pCurrent != NULL;

    if ( success )
    {
        pCurrent->data = data;
        pCurrent->next = *pHead;
        *pHead = pCurrent;
    }

    return success;
 }

 void out( SLLI *pHead )
 {
    for ( ; pHead != NULL; pHead = pHead->next )
    {
        printf( "%d -> ", pHead->data );
    }

    puts( "null" );
 }

int main(void) 
{
    const int N = 10;

    SLLI *pHead = NULL;

    for ( int i = N; i != 0; --i )
    {
        insert( &pHead, 10 * i );
    }

    out( pHead );

    SLLI *pSecondHead = OddNodes( &pHead );

    out( pHead );
    out( pSecondHead );

    return 0;
}
10 -> 20 -> 30 -> 40 -> 50 -> 60 -> 70 -> 80 -> 90 -> 100 -> null
20 -> 40 -> 60 -> 80 -> 100 -> null
10 -> 30 -> 50 -> 70 -> 90 -> null
#include <stdio.h>
#include <stdlib.h>

typedef struct SinglyLinkedListItem
{
    int data;
    struct SinglyLinkedListItem *next;
} SLLI;

SLLI * OddNodes( SLLI *pHead )
{
    int odd = 0;
    SLLI *pList = NULL;
    SLLI **pCurrent = &pList;

    for ( ; pHead != NULL; pHead = pHead->next )
    {
        if ( odd ^= 1 )
        {
            *pCurrent = malloc( sizeof( SLLI ) );
            ( *pCurrent )->data = pHead->data;
            ( *pCurrent )->next = NULL;
            pCurrent = &( *pCurrent )->next;
        }
    }

    return pList;
 }

 int insert( SLLI **pHead, int data )
 {
    SLLI *pCurrent = malloc( sizeof( SLLI ) );
    int success = pCurrent != NULL;

    if ( success )
    {
        pCurrent->data = data;
        pCurrent->next = *pHead;
        *pHead = pCurrent;
    }

    return success;
 }

 void out( SLLI *pHead )
 {
    for ( ; pHead != NULL; pHead = pHead->next )
    {
        printf( "%d -> ", pHead->data );
    }

    puts( "null" );
 }

int main(void) 
{
    const int N = 10;

    SLLI *pHead = NULL;

    for ( int i = N; i != 0; --i )
    {
        insert( &pHead, 10 * i );
    }

    out( pHead );

    SLLI *pSecondHead = OddNodes( pHead );

    out( pHead );
    out( pSecondHead );

    return 0;
}
10 -> 20 -> 30 -> 40 -> 50 -> 60 -> 70 -> 80 -> 90 -> 100 -> null
10 -> 20 -> 30 -> 40 -> 50 -> 60 -> 70 -> 80 -> 90 -> 100 -> null
10 -> 30 -> 50 -> 70 -> 90 -> null
SLLI * OddNodes( SLLI *pHead )
{
    int odd = 0;
    SLLI *pList = NULL;


    for ( SLLI *pCurrent = pList; pHead != NULL; pHead = pHead->next )
    {
        if ( odd ^= 1 )
        {
            if ( pCurrent == NULL )
            {
                pList = malloc( sizeof( SLLI ) );
                pList->data = pHead->data;
                pList->next = NULL;
                pCurrent = pList;
            }
            else
            {
                pCurrent->next = malloc( sizeof( SLLI ) );
                pCurrent->next->data = pHead->data;
                pCurrent->next->next = NULL;
                pCurrent = pCurrent->next;
            }
        }
    }

    return pList;
}
free() memory using a 'for' loop in a singly linked list

free() memory using a 'for' loop in a singly linked list


By : Edwin Raynor
Date : March 29 2020, 07:55 AM
wish help you to fix your issue This is my complete program: , You have a problem doing this:
Related Posts Related Posts :
  • Random function stuck on one number
  • printf following zeros to a certain degree
  • Measuring CPU clocks consumed by a process
  • How is a CRC32 checksum calculated?
  • Tips on redefining a register bitfield in C
  • Converting a program from c to bash script
  • Static library not included in resulting LLVM executable
  • What is the meaning of "wild pointer" in C?
  • Reading DWORD from binary file
  • Efficient way to find divisibility
  • Whats the fastest, portable way to hash pointers we know are pointer aligned to a fixed size int?
  • Why does my summation program behaves weird?
  • How to determine values saved on the stack?
  • Thread scheduling C
  • C - converting to 2s complement
  • wireless networks c program
  • From where does the uboot get the information about flash, RTC, RAM in uboot/kernel development
  • printf behaviour in C
  • Measure size and way-order of L1 and L2 caches
  • Efficient copy of entire directory
  • Efficient way to create/unpack large bitfields in C?
  • getnameinfo prototype asks for sockaddr not sockaddr_in?
  • Linked List Sorting with Strings In C
  • Typecasting a floating value or using the math.h floor* functions?
  • Problem implementing sorting algorithm in C with an array of structs
  • How to copy a ram_base file to disk efficiently
  • How to fix casting a pointer to an integer?
  • How to round floating point numbers to the nearest integer in C?
  • PIC C - Sending 200 values over USB, but it only sends 25 or so of them
  • How do you return a string from a function correctly in Dynamic C?
  • Monotonic clock on IRIX
  • setsockopt (sys/socket.h)
  • How to make C program wait (on Linux)?
  • i find a problem using atoi() method in ansi c?
  • Why is this array being initialized in an odd way?
  • How to execute commands in chroot?
  • Microsecond (or one ms) time resolution on an embedded device (Linux Kernel)
  • Question about variable definitions in functions
  • SMTP on C: STARTTLS via OpenSSL
  • fetch value of ipaddress
  • Binary expressions in C
  • Why do char * and char ** have the same value?
  • problem in allocating kernel memory by malloc() from user space?
  • dangling pointer, reason for value change after free()?
  • How to compile C program with multiple files in Xcode
  • Can you make an incrementing compiler constant?
  • Reading data from text file in C
  • SQLite's test code to production code ratio
  • Displaying an inverted pyramid of asterisks
  • sd spi mode in C language
  • printf("%2d") in C programming
  • Add a certain number of bytes to a void pointer in C
  • How should I protect against hard link attacks?
  • What's the difference between unsigned long/long/int in c/c++?
  • Get an input from keyboard without 'return' in C
  • How to convert if to switch-case in c
  • C: swapping two pointer value
  • What does \x mean in c/c++?
  • run a command line argument prog
  • Pass a dynamic structure by reference? [C]
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk