0

I have following struct

struct connection
{
    int *new_socket;
    int type;
    struct sockaddr_in address;
    char *request_line; 

};

And I created a pointer of connection struct like struct connection *con_obj=malloc(sizeof(struct connection)) now I like to allocate space for

 con_obj->request_line

Can I do this

*(con_obj->request_line)= malloc(sizeof(char )*val);

or do I need to do this

con_obj->request_line= malloc(sizeof(char )*val);//I don't think so

can anyone please tell this

user786
  • 3,902
  • 4
  • 40
  • 72
  • 3
    @kiner_shah Many StackOverflow users disagree with "you need to cast it to appropriate type" in case of C, indeed they recommend against it. https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc/605858#605858 – Yunnosch Oct 01 '21 at 07:13
  • 1
    You need: `con_obj->request_line = malloc(sizeof(char) * val)`. Why didn't you try it? Your compiler gives you valuable information. – Jabberwocky Oct 01 '21 at 07:19
  • 1
    @kiner_shah you don't _need_ to cast, but you _can_ cast it to the appropriate type, but such a cast is useless. – Jabberwocky Oct 01 '21 at 07:21
  • @Yunnosch, you're right. I just read this post: https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – kiner_shah Oct 01 '21 at 07:22
  • 1
    And do not forget to check `if (con_obj != NULL)` before trying to access `con_obj>request_line`. – kiner_shah Oct 01 '21 at 07:23
  • 1
    `*(con_obj->request_line)` this accesses a single `char` and your compiler should warn about "conversion making integer from pointer with different size" or similar. `con_obj->request_line` is a pointer and assigning an address is perfectly valid. If you don't get a warning for the first version, you need to increase warning level. – Gerhardh Oct 01 '21 at 07:29
  • Have a look at: [Member access operators](https://en.cppreference.com/w/c/language/operator_member_access) – Erdal Küçük Oct 01 '21 at 07:38

1 Answers1

0

The correct way is :

con_obj->request_line= malloc(val * sizeof(*con_obj->request_line));

You should test if the pointer con_obj is not NULL

Your fist version:

*(con_obj->request_line)= malloc(sizeof(char )*val);

invokes undefined befaviour as you dereference the unassigned poiter. The assignement itself is also wrong because you assign the char value with void *. You could discover it yourself if you have not ignored the compiler warnings. ALWAYS READ COMPILER WARNINGS. NEVER IGNORE THEM.

0___________
  • 60,014
  • 4
  • 34
  • 74