0

So in this snippet of C code, I have this situation which I don't fully comprehend. Basically, I want to modify the "tics" value inside of the newNode struct. The value I need to assign to it is "newAssignment." When I try to run this code, however, I get a seg-fault. The segfault doesn't occur EVERY time this code is ran, but it does get a seg-fault when temp-> next is null.

How do I assign newAssignment to newNode->tics without seg-faulting?

while(newNode->tics > temp->tics){
    int newAssignment = newNode->tics - temp->tics;
    newNode->tics = newAssignment;
    if(temp->next == NULL){
        break;
    }
    temp = temp->next;
}
idungotnosn
  • 2,001
  • 4
  • 29
  • 36
  • 3
    "The segfault doesn't occur EVERY time this code is ran, but it does get a seg-fault when temp-> next is null." Then it wouldn't hurt to see *why* it segfaults in that specific instance. – Dennis Meng Oct 20 '13 at 01:45
  • 6
    Do you check if `temp` and `newNode` are not null before you start the loop – Musa Oct 20 '13 at 01:47
  • If I comment out the line "newNode->tics = newAssignment", the seg fault doesn't occur. I don't think those values are ever null when the loop starts. – idungotnosn Oct 20 '13 at 01:49
  • Do you get a line number where the segmentation fault occurs? Where are `newNode` and `temp` declared. It will be hard to help without having more context. Are you being sure to set the last node to NULL when you set this up? – Jeremy West Oct 20 '13 at 01:49
  • 1
    @idungotnosn: Add an `assert`. It can't hurt. – icktoofay Oct 20 '13 at 01:49
  • Use `valgrind` to track down where your program goes wrong. Or see http://stackoverflow.com/questions/413477/is-there-a-good-valgrind-substitute-for-windows if you are on Windows. – ypnos Oct 20 '13 at 01:58
  • Related question [Segfault when attempting to nullify a pointer in C](http://stackoverflow.com/questions/19472613/segfault-when-attempting-to-nullify-a-pointer-in-c/19473159#19473159). Not the same question (no close because identical), but related and shows some of the data structures. – Jonathan Leffler Oct 20 '13 at 02:10
  • Are you positive this portion of code is the cullprit ? Running a debugger such as `ddd` will most probably help. – damienfrancois Oct 20 '13 at 08:16
  • 1
    Just because it works, when you comment the asssignment out, doesn't mean this line is faulty. I had this situation not to long ago, the actual error was the malloc()-command, where i allocated too less memory for a new list-element. I searched for this bug for hours – maja Oct 20 '13 at 09:22
  • I figured out the reason. Thanks for the help, and sorry about the vague nature of the question. I wasn't handling an edge case correctly in the code, so I went and handled that accordingly. Thanks for the help! – idungotnosn Oct 20 '13 at 19:06

0 Answers0