简体   繁体   中英

c11: use _Generic raise SIGSEGV

here is my code, I try sample code fromhere

#include <stdio.h>

#define type_idx(T) _Generic( (T), char: 1, int: 2, long: 3, default: 0)

int main(int argc, char *argv[]) {
    puts(type_idx("smth"));
}

the output in clion is:

/home/roroco/.CLion12/system/cmake/generated/c9a7a4c5/c9a7a4c5/Debug/ex/ex
Signal: SIGSEGV (Segmentation fault)

and here is my CMakeLists.txt

cmake_minimum_required(VERSION 3.3)
project(c)

set(CMAKE_C_COMPILER /usr/bin/gcc-4.9)
set(CMAKE_CXX_COMPILER /usr/bin/g++-4.9)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c11")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

The string literal "smth" decays into a pointer of type char* , which will get translated to the default clause of _Generic. You get the value 0, so your code is equivalent to

puts(0);

Which doesn't make any sense and will cause your program to crash.

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