Skip to content

Commit 04b551e

Browse files
authored
Fix mem leak in Source::newFromMemory() (#275)
* Fix mem leak in `Source::newFromMemory()` * Simplify
1 parent b9ac979 commit 04b551e

File tree

2 files changed

+12
-9
lines changed

2 files changed

+12
-9
lines changed

src/FFI.php

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -539,6 +539,8 @@ private static function init(): void
539539
typedef void (*FreeFn)(void* a);
540540
void vips_value_set_blob (GValue* value,
541541
FreeFn free_fn, void* data, size_t length);
542+
void* vips_blob_copy (const void *data, size_t length);
543+
void vips_area_unref (void *area);
542544
543545
const char* vips_value_get_ref_string (const GValue* value,
544546
size_t* length);
@@ -760,8 +762,7 @@ private static function init(): void
760762
761763
VipsSource* vips_source_new_from_descriptor (int descriptor);
762764
VipsSource* vips_source_new_from_file (const char* filename);
763-
VipsSource* vips_source_new_from_memory (const void* data,
764-
size_t size);
765+
VipsSource* vips_source_new_from_blob (void* blob);
765766
766767
typedef struct _VipsSourceCustom {
767768
VipsSource parent_object;

src/Source.php

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -64,17 +64,19 @@ public static function newFromFile(string $filename): self
6464
*/
6565
public static function newFromMemory(string $data): self
6666
{
67-
# we need to set the memory to a copy of the data that vips_lib
68-
# can own and free
69-
$n = strlen($data);
70-
$memory = FFI::vips()->new("char[$n]", false, true);
71-
\FFI::memcpy($memory, $data, $n);
72-
$pointer = FFI::vips()->vips_source_new_from_memory($memory, $n);
67+
$blob = FFI::vips()->vips_blob_copy($data, strlen($data));
68+
if ($blob === null) {
69+
throw new Exception("can't create source from memory");
70+
}
7371

72+
$pointer = FFI::vips()->vips_source_new_from_blob($blob);
7473
if ($pointer === null) {
74+
FFI::vips()->vips_area_unref($blob);
7575
throw new Exception("can't create source from memory");
7676
}
7777

78-
return new self($pointer);
78+
$source = new self($pointer);
79+
FFI::vips()->vips_area_unref($blob);
80+
return $source;
7981
}
8082
}

0 commit comments

Comments
 (0)