+ 1

What is wrong in this the invalid position is not working but it give correct output leaving that condition?

Pls tell me. https://code.sololearn.com/c9KIV45L4SZB/?ref=app

27th Sep 2019, 3:12 AM
Piyush Srivastava
Piyush Srivastava - avatar
3 Answers
+ 1
Assuming this is how you want to insert n1 --(i1)-> n2 --(i2)-> n3 --(i3)-> n4 --(i4)-> null where n# is an existing node an n1 is the head with i# being the positions you can insert a new node into, your condition should be (pos<index||pos>index+size-1) with index = 1, size = current size of list, allowing pos to only be [index, index+size-1] or [1, 1+4-1] == [1, 4]. The reason you don't see "invalid position" in the output is because of the segfault that happens right after (I'm not sure why sololearn doesn't tell you when a segfault happens) caused by dereferencing ptr with ptr->next/(*ptr).next when it is a nullptr on the iteration after ptr is the last node and ptr=ptr->next assigns a nullptr to ptr. You could flush the output to make sure the characters are sent to where they need to be for it to appear on the output: cout<<"invalid positions\n"<<flush; or cout<<"invalid positions"<<endl; and leave it at the segfault. But what if we want the program to terminate "gracefully"? We could exit(1) immediately after printing that error message so it never segfaults which isn't too bad or we could do it the C way and return a bool (false) and let the caller handle the error or we could throw a C++ exception. Another way to handle this without keeping track of the size using a global or iterating through the list is to end the while loop when ptr becomes nullptr: while (index != pos) { ptr = ptr->next; index++; if (ptr == nullptr) throw "Invalid position!"; // or return false; } On an unrelated note, I would recommend using new instead of malloc (if you don't have a reason not to) when using C++ because of several reasons mentioned here https://stackoverflow.com/questions/184537/in-what-cases-do-i-use-malloc-and-or-new and remember to free/delete your nodes when they are no longer in use even though here the list is used throughout the program and all the memory will be automatically freed after the program exits anyway.
27th Sep 2019, 6:18 AM
jtrh
jtrh - avatar
+ 1
What is segfault?
27th Sep 2019, 8:05 AM
Piyush Srivastava
Piyush Srivastava - avatar
+ 1
https://en.m.wikipedia.org/wiki/Segmentation_fault Segmentation fault, when trying to access invalid memory such as dereferencing a nullptr or a pointer that points to memory that you shouldn't be able to access (deleted/freed/dangling pointer) https://stackoverflow.com/questions/2346806/what-is-a-segmentation-fault
27th Sep 2019, 8:09 AM
jtrh
jtrh - avatar