Skip to content

Commit a5eb369

Browse files
committed
Merge branch 'bugfix/realloc_corruption_bug' into 'master'
heap: Fix bug when realloc moves data between heaps See merge request idf/esp-idf!1931
2 parents 417ef19 + b7fc067 commit a5eb369

File tree

2 files changed

+51
-1
lines changed

2 files changed

+51
-1
lines changed

components/heap/heap_caps.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -309,7 +309,7 @@ IRAM_ATTR void *heap_caps_realloc( void *ptr, size_t size, int caps)
309309
if (new_p != NULL) {
310310
size_t old_size = multi_heap_get_allocated_size(heap->heap, ptr);
311311
assert(old_size > 0);
312-
memcpy(new_p, ptr, old_size);
312+
memcpy(new_p, ptr, MIN(size, old_size));
313313
heap_caps_free(ptr);
314314
return new_p;
315315
}
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/*
2+
Generic test for realloc
3+
*/
4+
5+
#include <stdlib.h>
6+
#include <string.h>
7+
#include "unity.h"
8+
#include "sdkconfig.h"
9+
#include "esp_heap_caps.h"
10+
11+
12+
#ifndef CONFIG_HEAP_POISONING_COMPREHENSIVE
13+
/* (can't realloc in place if comprehensive is enabled) */
14+
15+
TEST_CASE("realloc shrink buffer in place", "[heap]")
16+
{
17+
void *x = malloc(64);
18+
TEST_ASSERT(x);
19+
void *y = realloc(p, 48);
20+
TEST_ASSERT_EQUAL_PTR(x, y);
21+
}
22+
23+
#endif
24+
25+
TEST_CASE("realloc move data to a new heap type", "[heap]")
26+
{
27+
const char *test = "I am some test content to put in the heap";
28+
char buf[64];
29+
memset(buf, 0xEE, 64);
30+
strlcpy(buf, test, 64);
31+
32+
char *a = malloc(64);
33+
memcpy(a, buf, 64);
34+
35+
// move data from 'a' to IRAM
36+
char *b = heap_caps_realloc(a, 64, MALLOC_CAP_EXEC);
37+
TEST_ASSERT_NOT_NULL(b);
38+
TEST_ASSERT_NOT_EQUAL(a, b);
39+
TEST_ASSERT(heap_caps_check_integrity(MALLOC_CAP_INVALID, true));
40+
TEST_ASSERT_EQUAL_HEX32_ARRAY(buf, b, 64/sizeof(uint32_t));
41+
42+
// Move data back to DRAM
43+
char *c = heap_caps_realloc(b, 48, MALLOC_CAP_8BIT);
44+
TEST_ASSERT_NOT_NULL(c);
45+
TEST_ASSERT_NOT_EQUAL(b, c);
46+
TEST_ASSERT(heap_caps_check_integrity(MALLOC_CAP_INVALID, true));
47+
TEST_ASSERT_EQUAL_HEX8_ARRAY(buf, c, 48);
48+
49+
free(c);
50+
}

0 commit comments

Comments
 (0)