lhahn
lhahn

Reputation: 1241

Simple android binary crashing with zlib

I made a simple android executable with CMake that links with the native zlib on the ndk. Everything compiles correctly, but when calling deflateInit I get a segmentation fault.

Here is the code:

main.cpp

#include <iostream>
#include <zlib.h>

int main()
{
    z_stream strm;
    deflateInit(&strm, Z_DEFAULT_COMPRESSION);
    std::cout << "it works!" << std::endl;
}

And the corresponding CMakeLists.txt

cmake_minimum_required(VERSION 3.8)
project(zlib-on-android)

add_executable(main main.cpp)

find_package(ZLIB REQUIRED)

set_target_properties(main
  PROPERTIES POSITION_INDEPENDENT_CODE ON)

target_link_libraries(main PUBLIC ZLIB::ZLIB)

I then compile with the following command:

cmake -H. -Bbuild -DCMAKE_SYSTEM_NAME=Android -DCMAKE_ANDROID_NDK=~/android-ndk-r17b -DCMAKE_ANDROID_STL_TYPE=c++_static -DCMAKE_SYSTEM_VERSION=16 -DCMAKE_ANDROID_NDK_TOOLCHAIN_VERSION=clang

Everything works fine. Then I do the following:

cd build
adb push main /data/local/tmp/.
adb shell
shell@device:/ $ cd /data/local/tmp
shell@device:/ $ ./main
[1] + Stopped (signal)     ./main

Does anyone know the reason? I am having a lot of trouble trying to hook up gdb with this executable. Since the same code works on my Macosx, I cannot understand why it does not work on android.

EDIT

For some reason the same code crashes on Macosx (the one that worked was a similar code). This is the error: bus error ./main

Upvotes: 0

Views: 335

Answers (1)

lhahn
lhahn

Reputation: 1241

Well, turns out that setting z_stream to zero fixes the problem.

#include <iostream>
#include <zlib.h>
#include <cstdlib>

int main()
{
    z_stream strm;
    std::memset(&strm, 0, sizeof(z_stream));
    deflateInit(&strm, Z_DEFAULT_COMPRESSION);
    std::cout << "it works!" << std::endl;
}

Upvotes: 1

Related Questions