Skip to content

Fix mem leak in Source::newFromMemory() #275

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 29, 2025
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Fix mem leak in Source::newFromMemory()
  • Loading branch information
kleisauke committed May 28, 2025
commit f9c4311808e1ab680bb125ecaa3a91ed3064648f
26 changes: 23 additions & 3 deletions src/Source.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,16 @@ class Source extends Connection
*/
public \FFI\CData $pointer;

/**
* Pointer to the underlying memory buffer when using
* @see Source::newFromMemory()
*
* Must be freed when no longer needed.
*
* @internal
*/
public ?\FFI\CData $memory = null;

public function __construct(\FFI\CData $pointer)
{
$this->pointer = FFI::vips()->cast(FFI::ctypes('VipsSource'), $pointer);
Expand Down Expand Up @@ -64,17 +74,27 @@ public static function newFromFile(string $filename): self
*/
public static function newFromMemory(string $data): self
{
# we need to set the memory to a copy of the data that vips_lib
# can own and free
# we need to set the memory to a copy of the data
$n = strlen($data);
$memory = FFI::vips()->new("char[$n]", false, true);
\FFI::memcpy($memory, $data, $n);
$pointer = FFI::vips()->vips_source_new_from_memory($memory, $n);

if ($pointer === null) {
\FFI::free($memory);
throw new Exception("can't create source from memory");
}

return new self($pointer);
$source = new self($pointer);
$source->memory = $memory;
return $source;
}

public function __destruct()
{
if ($this->memory !== null) {
\FFI::free($this->memory);
}
parent::__destruct();
}
}