I am currently developing a shared library in c++ for Android devices.
While writing tests I stumbled over strange behaviour which causes a segfault (dlfree), when calling the function in the example code.
First of all:
- The test which calls the library function links dynamically against the library.
- I also compiled the library and the test for linux and windows desktops. There they run without causing a segfault.
- Linking statically, the segfault does not appear on android.
Example code
typedef unsigned int DBRuleID;
typedef std::string DBRuleTarget;
struct DBRule {
DBRuleID id; //int
DBRuleTarget target; //std::string
};
//segfault variant
bool getRule(DBRuleID id, DBRule& rule) {
rule.target = "I am causing segfault!";
return true;
}
//working variant
bool getRule(DBRuleID id, DBRule& rule) {
//nothing is set
return true;
}
Segmentation Fault
Build fingerprint: 'generic/sdk/generic:3.0/HONEYCOMB/104254:eng/test-keys'
pid: 525, tid: 525 >>> /data/local/TestRulesDB <<<
signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr deadbaad
r0 deadbaad r1 0000000c r2 00000027 r3 00000000
r4 00000080 r5 aff46658 r6 00013000 r7 00000004
r8 00000004 r9 00013d3c 10 00000000 fp bec61a14
ip ffffffff sp bec61950 lr aff193e9 pc aff15f58 cpsr 00000030
#00 pc 00015f58 /system/lib/libc.so
#01 pc 00012d2a /system/lib/libc.so (dlfree)
EDIT - New findings
If the DBRule struct, which is passed to the function, is initialized with values everything works fine, otherwise it results in a segmentation fault.
//works
DBRule rule_1 = { 0, "target"};
//works not
DBRule rule_1 = { 0, ""};
//works not
DBRule rule_1;
Could someone please explain that to me? And what will be the best way to initialize it by default?
The questions are
- What am I doing wrong, what am I missing?
- Is there a mechanism which tries to delete allocated memory on the heap more than once?
I fired up valgrind on the desktop already, but there are no errors shown.
Thanks in advance!