Conditional expression can result in stack-use-after-scope
struct Foo {
public char a[4];
}
Foo get_foo () {
return { (char[]) "foo\0" };
}
string get_bar () {
bool b = true;
return b ? (string) get_foo ().a : "";
}
void get_manam () {
bool b = true;
{
unowned string s = b ? (string) get_foo ().a : "";
assert (s == "foo");
}
{
string s = b ? (string) get_foo ().a : "";
assert (s == "foo");
}
}
void main () {
assert (get_bar () == "foo");
get_manam ();
}
gchar*
get_bar (void)
{
gboolean b = FALSE;
const gchar* _tmp0_ = NULL;
gchar* _tmp2_;
gchar* result = NULL;
b = TRUE;
if (b) {
Foo _tmp1_ = {0};
get_foo (&_tmp1_);
_tmp0_ = (const gchar*) _tmp1_.a;
} else {
_tmp0_ = "";
}
_tmp2_ = g_strdup (_tmp0_);
result = _tmp2_;
return result;
}
_tmp0_
points to _tmp1_
which runs out of scope leaving _tmp0_
as invalid pointer.
$ valac test.vala -X -g -X -fsanitize=address,undefined
==112831==ERROR: AddressSanitizer: stack-use-after-scope on address 0x7fff850d6200 at pc 0x7f7fe3244ab7 bp 0x7fff850d6190 sp 0x7fff850d5938
READ of size 4 at 0x7fff850d6200 thread T0
#0 0x7f7fe3244ab6 in __interceptor_strlen ../../../../src/libsanitizer/sanitizer_common/sanitizer_common_interceptors.inc:389
#1 0x7f7fe30ec7d7 in g_strdup (/lib/libglib-2.0.so.0+0x757d7)
#2 0x563750586ace in get_bar test.vala.c:97
#3 0x563750586e86 in _vala_main test.vala.c:145
#4 0x563750586f06 in main test.vala.c:156
#5 0x7f7fe2541564 in __libc_start_main ../csu/libc-start.c:332
#6 0x56375058632d in _start (test+0x232d)
Address 0x7fff850d6200 is located in stack of thread T0 at offset 32 in frame
#0 0x5637505869a6 in get_bar test.vala.c:84
This frame has 1 object(s):
[32, 36) '_tmp1_' (line 91) <== Memory access at offset 32 is inside this variable
HINT: this may be a false positive if your program uses some custom stack unwind mechanism, swapcontext or vfork
(longjmp and C++ exceptions *are* supported)
SUMMARY: AddressSanitizer: stack-use-after-scope ../../../../src/libsanitizer/sanitizer_common/sanitizer_common_interceptors.inc:389 in __interceptor_strlen
Edited by Rico Tzschichholz