-1

I get segmentation fault when a structure member points to another structure. In details, my new structure is

typedef struct _sock_t{
  ir_socket_t *_socket;
  bool flag;
  extern_class obj;
  double *vect;
};

while the structure I want to point to is ir_socket_t socket;. In main(), if I do something like

  _sock_t *_sock ;
  _sock->_socket = &socket;

I then get segmentation fault. However,

  _sock_t _sock ;
  _sock._socket = &socket; 

works fine. What is wrong about the first approach.

P.S. Note that ir_socket_t is C not C++ structure.


UPDATE: If I also consider a C++ class object as new a structure member, then I still get segmentation fault at

int n(4);
_sock->obj.resize(4); // here segmentation fault

while there is no problem with the latter approach (no pointer). This happens even if I do _sock_t *_sock = (_sock_t *)malloc(sizeof(_sock_t));; using @Bathshebba answer.

What could be the issue please?

Note that _sock->vect= new double[n] works fine.

Note also that _sock = new _sock_t; works instead fine.

Courier
  • 920
  • 2
  • 11
  • 36
  • 1
    You haven't initialized `_sock`. – juanchopanza Sep 21 '16 at 07:10
  • `_sock_t *_sock`. You better learn about pointers before you proceed any further with your C programming. That's an uninitalised pointer and of course you can't dereference it. – kaylum Sep 21 '16 at 07:10
  • 1
    The variable `_sock` is not initialized to point to a valid (properly allocated) memory block. – barak manos Sep 21 '16 at 07:11
  • Please don't downvote on the grounds of obviousness. This question, IMHO, is well written. – Bathsheba Sep 21 '16 at 07:13
  • 1
    It's the difference between a *pointer* object and a *struct* object. `_sock_t *_sock ;` defines a *pointer* object which doesn't point anywhere; if you try to access the object "it points to" with`_sock->_socket`(quotes because it doesn't), you segfault. By contrast, `_sock_t _sock ;` defines an object of type `_sock_t` which has an existing field `_sock._socket`. – Peter - Reinstate Monica Sep 21 '16 at 07:14

1 Answers1

2

That's hardly surprising. In writing _sock_t *_sock all you've done is declare a pointer.

But it doesn't point to anything. The behaviour on dereferencing it (in your case via the pointer to member operator ->) is undefined.

You need to point it at allocated memory. Use malloc for this in C, and new in C++. Don't forget to call free and delete respectively once you're done with the pointer, else you'll leak memory.

Finally, (acknowledge @Karthick), it appears you're using a C++ compiler to compile C code: in C you'd need to write struct _sock_t *_sock;.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483