2

I try to initialize a structure pointer with another structure pointer inside by C programming, otherwise i get the segmentation fault. The structure is defined as below:

`struct gfcontext_t{
    char *fileContent;
    size_t fileLength;
    char *response;
    int socket_hd;
};

struct gfserver_t{
    char *serverName;
    int serverPort;
    int maxConnection;
    ssize_t (*handler)(struct gfcontext_t *, char *, void * );
    struct gfcontext_t *ctx;
    int status;
};

The initialization is give inside a function:

gfserver_t * gfserver_create(){
    struct gfserver_t *gfs;
    gfs=(gfserver_t*) malloc(sizeof(struct gfserver_t));
    ......//how to do the initialization?
    return gfs;
}`
14
  • 1
    Standard Warning : Please do not cast the return value of malloc() and family in C. Commented Jun 4, 2015 at 13:07
  • 3
    //how to do the initialization?...show existing efforts please Commented Jun 4, 2015 at 13:08
  • Standard Warning #2: Please do not use a C++ compiler to compile C code. If you need to use some C code in your C++ project, compile the C code (using a C compiler) as a static or dynamic object file, and then link that object file into your C++ project when you're compiling your C++ code (using a C++ compiler). Commented Jun 4, 2015 at 13:40
  • @undefinedbehaviour isn't that a bit overkill, if the code is in the C/C++ subset ? Commented Jun 4, 2015 at 13:44
  • @undefinedbehaviour Sorry but how did you know OP uses a C++ compiler? Commented Jun 4, 2015 at 13:48

1 Answer 1

1

Use:
gfs->ctx = malloc(sizeof(struct gfcontext_t));
or if you also want to initialize the gfcontext_t members to null
gfs->ctx = calloc(1, sizeof(struct gfcontext_t));

Sign up to request clarification or add additional context in comments.

2 Comments

Or gfs->ctx = calloc(1, sizeof *gfs->ctx);
@JeremyP Right, this is even better since you don't have to care about the type of ctx :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.