Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 625791c

Browse files
Free heap allocated C strings created with C.CString
2 parents fb1a2d8 + 1cfe4a9 commit 625791c

File tree

2 files changed

+18
-4
lines changed

2 files changed

+18
-4
lines changed

‎main_dynamic.go‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,17 @@ package main
55
/*
66
#cgo LDFLAGS: -L./lib -lhello
77
#include "./lib/hello.h"
8+
#include <stdlib.h>
89
*/
910
import "C"
11+
import "unsafe"
1012

1113
func main() {
12-
C.hello(C.CString("world"))
13-
C.whisper(C.CString("this is code from the dynamic library"))
14+
str1 := C.CString("world")
15+
str2 := C.CString("this is code from the dynamic library")
16+
defer C.free(unsafe.Pointer(str1))
17+
defer C.free(unsafe.Pointer(str2))
18+
19+
C.hello(str1)
20+
C.whisper(str2)
1421
}

‎main_static.go‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,17 @@ package main
66
/*
77
#cgo LDFLAGS: ./lib/libhello.a -ldl
88
#include "./lib/hello.h"
9+
#include <stdlib.h>
910
*/
1011
import "C"
12+
import "unsafe"
1113

1214
func main() {
13-
C.hello(C.CString("world"))
14-
C.whisper(C.CString("this is code from the static library"))
15+
str1 := C.CString("world")
16+
str2 := C.CString("this is code from the static library")
17+
defer C.free(unsafe.Pointer(str1))
18+
defer C.free(unsafe.Pointer(str2))
19+
20+
C.hello(str1)
21+
C.whisper(str2)
1522
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /