Skip to content

Commit 305e801

Browse files
committed
util: allow callers to reset custom allocators
Provide a utility to reset custom allocators back to their default. This is particularly useful for testing.
1 parent 671b244 commit 305e801

File tree

2 files changed

+15
-6
lines changed

2 files changed

+15
-6
lines changed

include/git2/common.h

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -364,7 +364,8 @@ typedef enum {
364364
*
365365
* > Set the memory allocator to a different memory allocator. This
366366
* > allocator will then be used to make all memory allocations for
367-
* > libgit2 operations.
367+
* > libgit2 operations. If the given `allocator` is NULL, then the
368+
* > system default will be restored.
368369
*
369370
* opts(GIT_OPT_ENABLE_UNSAVED_INDEX_SAFETY, int enabled)
370371
*

src/alloc.c

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,15 @@
1515

1616
git_allocator git__allocator;
1717

18+
static int setup_default_allocator(void)
19+
{
20+
#if defined(GIT_MSVC_CRTDBG)
21+
return git_win32_crtdbg_init_allocator(&git__allocator);
22+
#else
23+
return git_stdalloc_init_allocator(&git__allocator);
24+
#endif
25+
}
26+
1827
int git_allocator_global_init(void)
1928
{
2029
/*
@@ -24,15 +33,14 @@ int git_allocator_global_init(void)
2433
if (git__allocator.gmalloc != NULL)
2534
return 0;
2635

27-
#if defined(GIT_MSVC_CRTDBG)
28-
return git_win32_crtdbg_init_allocator(&git__allocator);
29-
#else
30-
return git_stdalloc_init_allocator(&git__allocator);
31-
#endif
36+
return setup_default_allocator();
3237
}
3338

3439
int git_allocator_setup(git_allocator *allocator)
3540
{
41+
if (!allocator)
42+
return setup_default_allocator();
43+
3644
memcpy(&git__allocator, allocator, sizeof(*allocator));
3745
return 0;
3846
}

0 commit comments

Comments
 (0)