1

I am trying to build an object of a struct but am getting a segmentation fault while assigning the values. After I build the object it will be passed by pointer into a list. Here is my implementation:

struct clientInfo {
  int client, a, b;
};
List *info=new List();

void thread(int which) {
  clientInfo *cI;
  cI->client=which;
  cI->a=4;
  cI->b=5;
  info->Append(cI);
}

During the execution of 'cI->client=which' a segmentation fault is produced. This project is being writting on the nachos platform for anyone that is familiar, however the definition of List is much the same as any linked list in C++. For anyone not familiar with nachos, 'void thread' is my 'int main'.

Thanks in advance.

cazzer
  • 1,726
  • 2
  • 18
  • 29
  • What does the `nachos` tag mean ? – cnicutar Mar 27 '12 at 07:06
  • @cnicutar: It's an academic operating system. For more info: http://www.cs.washington.edu/homes/tom/nachos/README – LihO Mar 27 '12 at 07:49
  • You should read a C++ book. Too many pointers, too many `new`. This is an attempt to make Java code in C++ and will only be painful. See the recommended books: http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – Matthieu M. Mar 27 '12 at 07:56

4 Answers4

4

clientInfo *cI; declares a pointer to an object of type clientInfo. It does not construct this object. You have to construct it before trying to access its members: cI = new clientInfo();.

LihO
  • 41,190
  • 11
  • 99
  • 167
2

You have to create the clientInfo *cI, like

clientInfo *cI = new clientInfo();
xanatos
  • 109,618
  • 12
  • 197
  • 280
  • 1
    your infinite wisdom is only surpassed by my infinite stupidity. Thank you for your quick response. – cazzer Mar 27 '12 at 07:08
2

The cI pointer is actually pointing "nowhere meaningful to you" when ci->members are assigned. Initilize the pointer to something existent (or allocate something for it) before use it.

Emilio Garavaglia
  • 20,229
  • 2
  • 46
  • 63
  • FWIW, depending on how the program's compiled, the pointer might point to a random memory location or to NULL. – bryce Mar 27 '12 at 07:34
1

You cannot directly assign values to a structure pointer.it should be given some allocation using new like :

 clientInfo *cI =new  clientInfo();

If you dont wish to do this just decalre the object rather than a pointer *cI. like below:

clientInfo cI;

Now you can directly assign values like cI.a=... and this data will be stroed on stack and not on heap.

Vijay
  • 65,327
  • 90
  • 227
  • 319