Skip to content

Memory leak: CString not freed in schema.go SchemaToSql() #619

@e-gineer

Description

@e-gineer

Description

The SchemaToSql() function in schema.go creates C.CString allocations that are never freed, causing a memory leak during schema import operations.

Current Code

commands = C.lappend(commands, unsafe.Pointer(C.CString(sql)))

Problem

C.CString() allocates memory on the C heap which must be explicitly freed with C.free(). The current code passes the result directly to lappend without ever freeing it.

Additionally, since the commands list is returned to PostgreSQL for processing, the strings need to be in PostgreSQL's memory context so they're properly managed.

Impact

  • Severity: Low
  • Frequency: Only during IMPORT FOREIGN SCHEMA (startup/schema refresh)
  • Memory leaked: ~100-1000 bytes per table imported

Proposed Fix

Use pstrdup() to copy the string into PostgreSQL's memory context:

cSql := C.CString(sql)
pSql := C.pstrdup(cSql)
C.free(unsafe.Pointer(cSql))
commands = C.lappend(commands, unsafe.Pointer(pSql))

This ensures:

  1. The temporary C heap allocation is freed
  2. The string is in PostgreSQL's memory context for proper lifecycle management

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions