8000 py/gc: Zero out all newly allocated memory to prevent stale pointers. · kevincon/circuitpython@1c0343f · GitHub
[go: up one dir, main page]

Skip to content

Commit 1c0343f

Browse files
committed
py/gc: Zero out all newly allocated memory to prevent stale pointers.
1 parent 2d9531a commit 1c0343f

File tree

2 files changed

+5
-8
lines changed

2 files changed

+5
-8
lines changed

py/gc.c

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -409,12 +409,12 @@ void *gc_alloc(size_t n_bytes, bool has_finaliser) {
409409
void *ret_ptr = (void*)(MP_STATE_MEM(gc_pool_start) + start_block * BYTES_PER_BLOCK);
410410
DEBUG_printf("gc_alloc(%p)\n", ret_ptr);
411411

412-
// zero out the additional bytes of the newly allocated blocks
412+
// Zero out all the bytes of the newly allocated blocks.
413413
// This is needed because the blocks may have previously held pointers
414414
// to the heap and will not be set to something else if the caller
415415
// doesn't actually use the entire block. As such they will continue
416416
// to point to the heap and may prevent other blocks from being reclaimed.
417-
memset((byte*)ret_ptr + n_bytes, 0, (end_block - start_block + 1) * BYTES_PER_BLOCK - n_bytes);
417+
memset((byte*)ret_ptr, 0, (end_block - start_block + 1) * BYTES_PER_BLOCK);
418418

419419
#if MICROPY_ENABLE_FINALISER
420420
if (has_finaliser) {
@@ -620,8 +620,8 @@ void *gc_realloc(void *ptr_in, size_t n_bytes, bool allow_move) {
620620
ATB_FREE_TO_TAIL(bl);
621621
}
622622

623-
// zero out the additional bytes of the newly allocated blocks (see comment above in gc_alloc)
624-
memset((byte*)ptr_in + n_bytes, 0, new_blocks * BYTES_PER_BLOCK - n_bytes);
623+
// zero out the bytes of the newly allocated blocks (see comment above in gc_alloc)
624+
memset((byte*)ptr_in + n_blocks * BYTES_PER_BLOCK, 0, (new_blocks - n_blocks) * BYTES_PER_BLOCK);
625625

626626
#if EXTENSIVE_HEAP_PROFILING
627627
gc_dump_alloc_table();

py/malloc.c

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -114,10 +114,7 @@ void *m_malloc_with_finaliser(size_t num_bytes) {
114114

115115
void *m_malloc0(size_t num_bytes) {
116116
void *ptr = m_malloc(num_bytes);
117-
if (ptr == NULL && num_bytes != 0) {
118-
return m_malloc_fail(num_bytes);
119-
}
120-
memset(ptr, 0, num_bytes);
117+
// memory is already cleared by gc_alloc
121118
return ptr;
122119
}
123120

0 commit comments

Comments
 (0)
0