开发者

Function pointer assignment, why does calling this function via pointer result in seg fault?

开发者 https://www.devze.com 2023-03-10 07:12 出处:网络
I have this struct defined: typedef struct Socket_s { ... SocketConnectFuncConnect; ... }Socket; where SocketConnectFunc is defined as:

I have this struct defined:

typedef struct Socket_s
{
  ...
  SocketConnectFunc         Connect;
  ...
}Socket;

where SocketConnectFunc is defined as:

typedef Socket_Return (*SocketConnectFunc) (void * self);

When initialising a Socket structure, I call this:

void Init(Socket * sock)
{
    sock = (Socket *)malloc(sizof(Socket));
    if(sock)
      sock->Connect = SocketConnect;
}

But then, when I attempt to call sock->Connect() I get segmentation开发者_StackOverflow fault, and the function isn't even entered. Is there a problem in the way I assigned sock->Connect?

NB. Socket_Return is an enum (typedef enum {SUCCESS,FAIL} Socket_Return)


You need to pass the address of the pointer. Passing just the pointer you can't change it in the caller

void Init(Socket ** sock) {
    *sock = malloc(sizeof **sock); /* don't cast the return value of malloc! */
    if (*sock)
        (*sock)->connect = SocketConnect;
}

And call it like so

struct Socket_s *mysock;
Init(&mysock);


I would write it like this:

Socket * CreateSocket() {
    Socket * sock = (Socket *) malloc( sizeof( Socket ) );
    if ( sock ) {
      sock->Connect = SocketConnect;
    }
    return sock;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消