Home > database >  C Segmentation fault when changing (int32_t *) pointer within method call
C Segmentation fault when changing (int32_t *) pointer within method call

Time:05-11

I'm programming a server - client application with a shared utils.cpp.

So the server and client use the (in utils.h) predefined methods:

int listening_socket(int port);
int connect_socket(const char *hostname, const int port);
int accept_connection(int sockfd);
int recv_msg(int sockfd, int32_t *operation_type, int64_t *argument);
int send_msg(int sockfd, int32_t *operation_type, int64_t *argument);

So far, so good.

But since the recv_msg() just returns if it was successful or not I need to handle the transmitted operation_type and argument via pointer modification. At this point I am kind of lost.

My goal is to set the method parameters (the int32_t *operation_type and int64_t *argument pointer) to the transmitted values. In server.cpp I have initialised the int32_t * and int64_t * in order to pass them into the recv_msg() method (also tried to give them a value e.g. = 0).

server.cpp:

...
int32_t *operation_type; // with = 0; also Segmentation fault
int64_t *operation_type; // with = 0; also Segmentation fault

if (recv_msg(server_socket, operation_type, argument) == 0)
        printf("In server.cpp: operation_type: %" PRId32 " and argument: %" PRId64 " \n", operation_type, argument);

In utils.cpp the method I am trying to change the pointer's value via:

int recv_msg(int sockfd, int32_t *operation_type, int64_t *argument) {
   // some buffer and read() stuff...
   // trying to change pointer's value 
   operation_type = (int32_t *)1;
   // also tried 
   *operation_type = 1;
   // and same thing with the int64_t * argument pointer
   int64_t  argu = message.argument(); // also tried this
    *argument = argu;

    printf("In utils.cpp: operation_type: %" PRId32 " and argument: %" PRId64" \n", operation_type, argument);

Ether I don't change the points values, so in method they have the wanted value, but after executing the recv_msg() the points value is 0 again or I get a Segmentation fault.

I understand the basics of pointers and references, but I am used to Java and new to the "*" and "&" prefixes.

My question: How do I can modify pointers which are passed as parameters in a imported method, or I am ready the int32_t and int64_t wring?

CodePudding user response:

Pointers are variables that should be use to point to some allocated memory.

In your initialization, you made your pointers point to NULL, i.e, no memory.

And after that you are trying to change the value of nothing. That's why you are getting a segmentation fault.

You should either:

Declare some local variables and make your pointers point to them. Something like:

int32_t local_type_operation;
type_operation = &local_type_operation;

Or use some dynamic memory allocation function to allocate some memory to point to (search about malloc).

  • Related