C++ – changed address of passed pointer

I have a program that i made, it is working very well on current system(RHEL).
And I try to porting this program to another system that is also RHEL with same OS version and same compiler version.
It compiled well, but run this program on new system, I got segmentation fault.

Here’s my gdb log

(gdb) where
  #0  0x00007f1dd11ab8e2 in MyClass::send (header=Cannot access memory at address 0x7fff0eca6048
  #1  0x00007f1dd11aad8a in MyClass::request (header=0x7f1dd09c2018) at myclass.cpp:823
   ...

(gdb) r
   ...

   Breakpoint 1, MyClass::request (header=0x7ffff4b16018) at myclass.cpp:820
(gdb) p header
   $1 = (Header *) 0x7ffff4b16018
(gdb) n
   823 in myclass.cpp
(gdb) p header
   $2 = (Header *) 0x7ffff4b16018
(gdb) n
   Program received signal SIGSEGV, Segmentation fault.
   0x00007ffff52ff8e2 in Telegram::send (header=Cannot access memory at address 0x7fffff3fd328
    ) at myclass.cpp:1059
   1059 in myclass.cpp
(gdb) p header
   Cannot access memory at address 0x7fffff3fd328

You can see the address of header is changed 0x7ffff4b16018 to 0x7fffff3fd328
there is no code re-assigning pointer to header.
I just passed the pointer to parameter and set the values and passed the pointer to parameter again.
How can it happen?

the code is here

int MyClass::request(Header *header, char * r_psystem_id, char * r_lsystem_id, char * r_group_id, char * r_bp_id, char *tr_ccd, void *src, int fmt[][5], int fields, int sockfd)) {
    if(sockfd < 0) return 0 ;

    Body body = Body();
    body.format_data(src, fmt, fields);

    // initialize header
    header->tglen = header->getLength() + body.getLength() - LEN_TGLEN;
    memcpy(header->r_psystem_id, r_psystem_id, LEN_SYSTEM_ID);
    memcpy(header->r_group_id, r_group_id, LEN_GROUP_ID);
    memcpy(header->r_lsystem_id  , r_lsystem_id, LEN_SYSTEM_ID);
    memcpy(header->r_group_id    , r_group_id  , LEN_GROUP_ID                       );
    memcpy(header->r_bp_id, r_bp_id, LEN_BP_ID);
    makeUUID(header->uuid);
    memcpy(header->tr_ccd, tr_ccd, LEN_TR_CCD);
    header->tr_tcd[0] = 'S';
    DateTime::curdate(header->tr_dt);
    DateTime::curutime(header->tr_tmd); 
    header->user_data_len = body.getLength();  // 1st break point here 820 line

    if (send(header, &body, sockfd) != 0)
    {
        perror("socket write error: ");
        return -1;
    }
    return 0;
}

int MyClass::send(Header *header, Body *body, int sockfd)  // segfault here 1059 line
{
    if(sockfd < 0) return 0 ;
    char sendbuf[MAX_MESSAGE_LEN + 1] = {0x00,};
    int offset = 0;

    ...
    // send message code below
}

Anyone experienced same problem?

—-edit—–
I put whole code of request method.


Source: gcc

Leave a Reply