-
Notifications
You must be signed in to change notification settings - Fork 200
Expand file tree
/
Copy pathReallocShrink.C
More file actions
29 lines (25 loc) · 940 Bytes
/
Copy pathReallocShrink.C
File metadata and controls
29 lines (25 loc) · 940 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// RUN: %cladclang %s -I%S/../../include -oReallocShrink.out 2>&1 | %filecheck %s
// RUN: ./ReallocShrink.out | %filecheck_exec %s
// Shrinking in-place realloc: the reverse sweep must resize the buffer (and its
// adjoint) back to the pre-realloc size so the pre-realloc reads stay in bounds
// and the adjoint accumulates correctly. Runs Memcheck-clean under the valgrind
// CI row.
#include "clad/Differentiator/Differentiator.h"
#include <cstdlib>
// res = (x + x*x) + x -> dres/dx = 2 + 2x ; at x = 3 -> 8
double shrink_realloc(double x) {
double* p = (double*)malloc(2 * sizeof(double));
p[0] = x;
p[1] = x * x;
double res = p[0] + p[1];
p = (double*)realloc(p, 1 * sizeof(double)); // shrink 2 -> 1
res += p[0];
free(p);
return res;
}
int main() {
auto g = clad::gradient<clad::opts::disable_tbr>(shrink_realloc, "x");
double dx = 0;
g.execute(3.0, &dx);
printf("{%.2f}\n", dx); // CHECK-EXEC: {8.00}
}