Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there a Segmentation Fault in this code?

#include <iostream>
#include <string>
using namespace std;

//create a struct to have model number and name and a pointer to next book
struct comp
{
    string nam;
    int mnum;
    comp* next; 
};

// define comp pointer to compPtr
typedef comp* compPtr;

int main()
{
    compPtr head = NULL;
    compPtr last = NULL;

    if (head == NULL)
    {
        compPtr temp;
        temp->nam = "Dell";
        temp->mnum = 45215;
        temp->next = NULL;
        head = temp;
        last = temp;
    }
    if (head != NULL)
    {
        compPtr temp1;
        temp1->nam = "Mac";
        temp1->mnum = 1255;
        temp1->next = NULL;
        last->next = temp1;
        last = temp1;
    }

    compPtr compnext;
    compnext = head;
    if (compnext == NULL)
    {
        cout<<"NO COMPUTERS";
    }
    else
    {
        while(compnext != NULL)
        {
            cout<<compnext->nam<<endl;
            cout<<compnext->mnum<<endl;
            compnext = compnext->next;
        }
    }
}
like image 309
hbhojwani Avatar asked Jan 25 '26 12:01

hbhojwani


1 Answers

Why is there a Segmentation Fault in this code?

Don't "hide" pointers behind a typedef -- it will only confuse you.

Your code is equivalent to:

comp *temp;          // Note: does not point *anywhere*.
temp->nam = "Dell";  // Dereferencing uninitialized pointer, undefined behavior,
                     // often crash.
like image 112
Employed Russian Avatar answered Jan 27 '26 02:01

Employed Russian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!