Skip to content

Commit 170234f

Browse files
committed
fix: properly allocate and free the memory
1 parent 2b6e248 commit 170234f

File tree

1 file changed

+9
-2
lines changed

1 file changed

+9
-2
lines changed

go-src/publiccode-parser-wrapper.go

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,10 @@ func ParseString(content *C.char) *C.struct_ParseResult {
3737

3838
pc, err := parser.ParseStream(strings.NewReader(goString))
3939

40-
result := (*C.struct_ParseResult)(C.malloc(C.size_t(C.sizeof_struct_ParseResult)))
40+
result := (*C.struct_ParseResult)(C.calloc(1, C.size_t(C.sizeof_struct_ParseResult)))
41+
result.Error = nil
42+
result.Errors = nil
43+
result.ErrorCount = 0
4144

4245
if err != nil {
4346
result.Error = C.CString(err.Error())
@@ -48,7 +51,7 @@ func ParseString(content *C.char) *C.struct_ParseResult {
4851

4952
if errCount > 0 {
5053
cErrors := C.malloc(C.size_t(errCount) * C.size_t(unsafe.Sizeof(uintptr(0))))
51-
errorsSlice := unsafe.Slice((**C.char)(cErrors), errCount)
54+
errorsSlice := (*[1 << 28]*C.char)(cErrors)[:errCount:errCount]
5255

5356
for i, e := range validationRes {
5457
errorsSlice[i] = C.CString(e.Error())
@@ -69,6 +72,7 @@ func ParseString(content *C.char) *C.struct_ParseResult {
6972
}
7073

7174
result.Data = C.CString(string(jsonData))
75+
7276
return result
7377
}
7478

@@ -91,9 +95,12 @@ func FreeResult(result *C.struct_ParseResult) {
9195
for i := 0; i < int(result.ErrorCount); i++ {
9296
if errorsSlice[i] != nil {
9397
C.free(unsafe.Pointer(errorsSlice[i]))
98+
errorsSlice[i] = nil
9499
}
95100
}
96101
C.free(unsafe.Pointer(result.Errors))
102+
result.Errors = nil
103+
result.ErrorCount = 0
97104
}
98105
}
99106

0 commit comments

Comments
 (0)