简体   繁体   中英

Crash when calling C++ function from C

I have a C++ library function which I am calling from a C function. The call passes in a C data-structure that is accessed by the C++ code. My program crashes in the C++ code when accessing the C data-structure. I've followed all the instructions in C++ faq related to mixing C-to-C++.

The crash happens on a centos7 machine. Running the same code in debug mode does not result in a crash. The same code running on Ubuntu (16.04) does not result in a crash. Here's the GDB analysis of the crash.

(gdb) frame 5
#5  0x00007fc28e79226e in ngx_http_setup_handler (r=0x2469040)
    at /opt/platform/nginx-noname-module.c:201
201       return ModProcessGetApi(r);
(gdb) p r->unparsed_uri
$1 = {len = 15, data = 0x24572c4 "/__xx/stats/all HTTP/1.1\r\nUser-Agent"}
(gdb) down
#4  0x00007fc28e7945b4 in ModProcessGetApi (r=r@entry=0x2469040)
    at /opt/platform/nginx-body-handler.cc:274
274   ss_rval_t rv = ProcessGetRequest(r, data, &dsize);
(gdb) p r->unparsed_uri
$2 = {len = 38105792, data = 0xf <Address 0xf out of bounds>}
(gdb)

As soon as the execution enters the C++ code, the C data structure shows address out of bounds. Here's is the glue code for c-to-c++ functions.

#if __cplusplus
extern "C" {
#endif

#include <nginx.h>
#include <ngx_core.h>
#include <ngx_log.h>
#include <ngx_http.h>

ngx_int_t ModPostRequestBodyHandler(ngx_http_request_t *r);
ngx_int_t ModProcessGetApi(ngx_http_request_t* r);

#if __cplusplus
}
#endif

I would appreciate it if someone can shed some light on this. Are there any compiler options I need to use when mixing C and C++ code so that the C++ code can access the C data-structure properly? Here's the OS and compiler info:

Centos Version: Crash happens

OS: Centos 7, C++: g++ 4.8.5

Ubuntu Versions: Crash does not happen.

OS: Ubuntu 16.04, C++: g++ 5.4.0

Not sure if it matters but I am running my app in a docker container on both OSes.

It turns out my c++ and C libraries were getting compiled with different #defines, as a result, the C data-structure was different in both the libraries. This results in misaligned access on the c++ side. This problem could have happened in two c libraries as well.

Thanks to all who responded.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM