Search code examples
cgccdata-structureslinked-listcomputer-science

How to iterate through a linked list without buffer overflow?


I wrote

while (ptr->next != NULL) {
        //code here
        ptr = ptr->next;
    }

and AddressSanitizer is throwing an heap-buffer overflow error.

I added

if (ptr->next != NULL) {
    while (ptr->next != NULL) {
        //code here
        ptr = ptr->next;
    }
}

hoping that maybe it would avoid reading a unallocated address, but now AddressSanitizer is terminating my program with SEGV. I'm not really sure how to fix this as I'm new to programming in C, any insights would be very helpful. Thank you!


Solution

  • You can do

    while(ptr != NULL) {
      // code
      ptr = ptr->next;
    }
    

    or even

    for(type* i = ptr; i != NULL; i = i->next) {
      // code
    }