Managing memory across language boundaries is a crucial aspect of system design, especially when integrating Go with other programming languages such as C or C++. When utilizing foreign function interfaces (FFI), understanding how to allocate, free, and manage memory is essential to avoid memory leaks and ensure efficient resource allocation.
In Go, memory is managed automatically via garbage collection, but interfacing with languages like C requires manual memory management. Here is an example showing how to allocate and free memory when using C code from Go:
package main
/*
#include
#include
char* allocateMemory(int size) {
return (char*)malloc(size);
}
void freeMemory(char* ptr) {
free(ptr);
}
*/
import "C"
import (
"fmt"
"unsafe"
)
func main() {
// Allocate memory using C
size := 100
cPtr := C.allocateMemory(C.int(size))
defer C.freeMemory(cPtr)
// Use the memory
goSlice := (*[100]C.char)(cPtr)
for i := 0; i < size; i++ {
goSlice[i] = C.char('A' + C.char(i % 26))
}
fmt.Println("Allocated memory content:", C.GoStringN(cPtr, C.int(size)))
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?