Question

I'm playing around with calling C code in go. When I try to use printf from go however, I get a warning about the format string not being a string literal:

package main

// #include <stdio.h>
import "C"

func main() {
    C.printf(C.CString("Hello world\n"));
}

Warning:

warning: format string is not a string literal (potentially insecure) [-Wformat-security]

How can I pass a string literal into a C function like printf? Is there a function similar to C.CString() that I can use, or is it impossible and I should ignore this warning?

Was it helpful?

Solution

When using printf, the format string is better to be a string literal and not a variable. And C.CString is coverted char pointer by go runtime. And also you may not use variadic arguments of printf in latest go. In other case, if you want to remove the warnings, Use type cast:

package main

/*
typedef const char* const_char_ptr;
#include <stdio.h>
*/
import "C"

func main() {
    C.puts((C.const_char_ptr)(C.CString("foo")))
}

EDIT

Note that call free for C.CString.

package main

/*
typedef const char* const_char_ptr;
#include <stdio.h>
*/
import "C"
import "unsafe"

func main() {
    ptr := (C.const_char_ptr)(C.CString("foo"))
    defer C.free(unsafe.Pointer(ptr))
    C.puts(ptr)
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top