﻿---
title: Memory and errors
description: Who owns each pointer in the C SDK, how handles live and die, how to read a failure, and which calls are thread-safe.
url: https://help.tangerina.io/deformable/v0.6.0/user-guides/c/memory-and-errors/
---

# Memory and errors – C SDK – Deformable v0.6.0

Every function of the C SDK follows the same rules for memory, errors and threads. This page explains them with
examples. For the documentation of each status code, error function and cancel flag, see
[status codes](https://help.tangerina.io/deformable/v0.6.0/api-references/c/errors/#deformablestatus),
[last error](https://help.tangerina.io/deformable/v0.6.0/api-references/c/errors/#deformable_last_error_message) and
[cancel flags](https://help.tangerina.io/deformable/v0.6.0/api-references/c/errors/#deformablecancelflag) on the Errors page of the C API
Reference.

## Memory

Four kinds of memory cross the interface. The library never frees your memory, and you never free the library's
arrays.

| Memory | Owner | Valid until |
|---|---|---|
| Arrays and structs you pass in | You | The call returns. The library copies what it keeps. |
| Handles, such as `DeformableScene *` | You, through the matching `_destroy` function | You destroy the handle. |
| Arrays the library lends, such as node positions | The library | The rule of the function that lent them; see below. |
| Static strings: the version and the preset names | The library | The process ends. |

### Arrays you pass in

You pass an array as a pointer and a count. The library reads it during the call only, so you can free or reuse
the memory as soon as the call returns. A count of 0 accepts any pointer, `NULL` included. With a count above 0, a
`NULL` pointer gives `DEFORMABLE_STATUS_NULL_POINTER`.

Fixed groups keep their C array type. A tetrahedron is `uint32_t[4]`, so an array of tetrahedrons is a pointer to
arrays:

```c
const DeformableVector3 positions[4] = {{0, 0, 0}, {1, 0, 0}, {0, 1, 0}, {0, 0, 1}};
const uint32_t tetrahedrons[1][4] = {{0, 2, 1, 3}};
DeformableTetrahedralMeshView mesh = {positions, 4, tetrahedrons, 1};
```

The structs that end in `View`, such as `DeformableTetrahedralMeshView`, hold borrowed pointers. They own nothing.

### Handles

A handle is an opaque pointer. A `_create` function or a tool writes a new handle to its last argument, and the
matching `_destroy` function frees it. Every `_destroy` function accepts `NULL` and does nothing then.

| Handle | Made by | Read with | Freed by |
|---|---|---|---|
| `DeformableScene` | `deformable_scene_create` | the `deformable_scene_` functions | `deformable_scene_destroy` |
| `DeformableCancelFlag` | `deformable_cancel_flag_create` | `deformable_cancel_flag_set`, `deformable_cancel_flag_is_set` | `deformable_cancel_flag_destroy` |
| `DeformableTetrahedralization` | `deformable_tetrahedralize` | `deformable_tetrahedralization_view` | `deformable_tetrahedralization_destroy` |
| `DeformableTriangulation` | `deformable_triangulate` | `deformable_triangulation_view` | `deformable_triangulation_destroy` |
| `DeformableTetrahedralMesh` | `deformable_extrude`, `deformable_span_layers` | `deformable_tetrahedral_mesh_view` | `deformable_tetrahedral_mesh_destroy` |
| `DeformableTriangleMesh` | `deformable_autocage` | `deformable_triangle_mesh_view` | `deformable_triangle_mesh_destroy` |
| `DeformablePolygonMesh` | `deformable_splinters_from_image` | `deformable_polygon_mesh_view` | `deformable_polygon_mesh_destroy` |
| `DeformableMeshIssueList` | `deformable_verify_surface` | `deformable_mesh_issue_list_issues` | `deformable_mesh_issue_list_destroy` |
| `DeformableBoundaryFaces` | `deformable_boundary_faces` | `deformable_boundary_faces_masks` | `deformable_boundary_faces_destroy` |
| `DeformableMaterialRegionIndices` | `deformable_material_region_indices` | `deformable_material_region_indices_values` | `deformable_material_region_indices_destroy` |
| `DeformableSurfaceEmbedding` | `deformable_embed_surface` | `deformable_surface_embedding_view` | `deformable_surface_embedding_destroy` |
| `DeformableDeformedSurface` | `deformable_deformed_surface_create` | `deformable_deformed_surface_view` | `deformable_deformed_surface_destroy` |

Object and material handles are different: they are `uint32_t` values that count up from 0 in the order you
create them. They belong to their scene, and you never free them.

### Arrays the library lends

The library lends an array as a pointer and a count, or as a view struct. You read it in place and copy what you
keep. When the count is 0, do not read the pointer.

| Lent by | Valid until |
|---|---|
| A `_view` function or a getter of a result handle, such as `deformable_tetrahedralization_view` | The handle is destroyed. |
| A per-frame output of a scene, such as `deformable_scene_node_positions` | The next call of the same function on the same scene, or its destruction. |
| `deformable_deformed_surface_view` | The next `deformable_surface_embedding_deform` into the same handle, or its destruction. |
| `deformable_last_error_message` | The next call on the same thread that returns a `DeformableStatus`. |

Each per-frame output function of a scene has one buffer. So the positions of one object stay valid while you
read the states and the face events of the same frame. A second call to `deformable_scene_node_positions`,
even for another object, replaces the first array: copy it first when you need two at once. A step does not
change a lent array. It only makes its values old.

## Status codes and the last error

Every function that can fail returns a `DeformableStatus`, an `int32_t`. It is `DEFORMABLE_STATUS_OK` (0) on success
and a positive code on failure. On failure, the function writes nothing to its output pointers, so a handle you set
to `NULL` stays `NULL`.

The library also records the failure as the *last error* of the calling thread. A call that succeeds clears it.
Three functions read and reset it:

- `deformable_last_error_message` returns a UTF-8 message, such as `tetrahedron 0 is inverted`. It is the empty
  string when the latest call on this thread succeeded. It never changes the last error.
- `deformable_last_error_details` writes a `DeformableErrorDetails`: the status, and up to two indices,
  `first_index` and `second_index`, that name the element the failure is about, such as a tetrahedron, a polygon or
  the two vertices of an edge. They are 0 when the status names no element. This call never changes the last error
  either, even when it fails itself.
- `deformable_last_error_clear` empties the last error, so that only the next failure is reported.

This program makes the library refuse a tetrahedron, then reads the error:

```c
#include <stdio.h>

#include "deformable.h"

int main(void) {
    DeformableScene *scene = NULL;
    DeformableMaterialParameters parameters;
    DeformableObjectOptions options;
    DeformableTetrahedronMaterials materials = {0};
    DeformableErrorDetails details;
    uint32_t object = 0;

    deformable_scene_create(&scene);
    deformable_material_parameters_default(&parameters);
    deformable_object_options_default(&options);
    deformable_scene_add_material(scene, &parameters, &materials.material);

    /* One tetrahedron with right-handed corners: the library expects left-handed ones. */
    const DeformableVector3 positions[4] = {{0, 0, 0}, {1, 0, 0}, {0, 1, 0}, {0, 0, 1}};
    const uint32_t tetrahedrons[1][4] = {{0, 1, 2, 3}};
    DeformableTetrahedralMeshView mesh = {positions, 4, tetrahedrons, 1};

    DeformableStatus status = deformable_scene_add_object(scene, &mesh, &materials, &options, &object);
    deformable_last_error_details(&details);
    printf("status %d, tetrahedron %u: %s\n", (int)status, (unsigned)details.first_index,
           deformable_last_error_message());

    /* Swapping two corners makes it left-handed, and the call succeeds. */
    const uint32_t fixed[1][4] = {{0, 2, 1, 3}};
    mesh.tetrahedrons = fixed;
    status = deformable_scene_add_object(scene, &mesh, &materials, &options, &object);
    printf("status %d, object %u, message \"%s\"\n", (int)status, (unsigned)object, deformable_last_error_message());

    deformable_scene_destroy(scene);
    return 0;
}
```

```text
status 13, tetrahedron 0: tetrahedron 0 is inverted
status 0, object 0, message ""
```

The functions that cannot fail return their value directly: `deformable_version`, `deformable_last_error_message`,
`deformable_material_preset_count` and the `_destroy` functions.

### Clean up after a failure

Because a failed call writes nothing and every `_destroy` function accepts `NULL`, a chain of calls needs only one
cleanup path. This function fills a cage with tetrahedrons and adds them to a scene:

```c
/* Fills cage with tetrahedrons and adds them as an object. Returns 0 on success, 1 after printing the error. */
static int add_solid(DeformableScene *scene, const DeformableTriangleMeshView *cage, uint32_t material,
                     uint32_t *object) {
    DeformableTetrahedralization *tetrahedralization = NULL;
    DeformableTetrahedralizationView view;
    DeformableTetrahedralizeParameters parameters = {0};
    DeformableTetrahedronMaterials materials = {DEFORMABLE_MATERIAL_ASSIGNMENT_UNIFORM, material, NULL, 0};
    DeformableObjectOptions options;
    int result = 0;

    parameters.maximum_edge_length = 0.5;
    if (deformable_anisotropy_default(&parameters.anisotropy[0]) != DEFORMABLE_STATUS_OK ||
        deformable_anisotropy_default(&parameters.anisotropy[1]) != DEFORMABLE_STATUS_OK ||
        deformable_object_options_default(&options) != DEFORMABLE_STATUS_OK ||
        deformable_tetrahedralize(cage, &parameters, NULL, &tetrahedralization) != DEFORMABLE_STATUS_OK ||
        deformable_tetrahedralization_view(tetrahedralization, &view) != DEFORMABLE_STATUS_OK ||
        deformable_scene_add_object(scene, &view.mesh, &materials, &options, object) !=
            DEFORMABLE_STATUS_OK) {
        fprintf(stderr, "add_solid: %s\n", deformable_last_error_message());
        result = 1;
    }
    /* Still NULL when deformable_tetrahedralize failed; destroy functions ignore NULL. */
    deformable_tetrahedralization_destroy(tetrahedralization);
    return result;
}
```

When the cage is not closed, `deformable_tetrahedralize` fails, the rest of the chain does not run, and the function
prints:

```text
add_solid: cage not closed, outward and free of self-intersections
```

### The status codes

The codes fall into a few groups. [`DeformableStatus`](https://help.tangerina.io/deformable/v0.6.0/api-references/c/errors/#deformablestatus) in the
C API Reference documents each one.

| Codes | Group | Examples |
|---|---|---|
| 1 to 3 | Any call | `DEFORMABLE_STATUS_NULL_POINTER`, `DEFORMABLE_STATUS_INVALID_ARGUMENT` (an undefined enumeration value, a misaligned pointer or an unknown preset name), `DEFORMABLE_STATUS_PANICKED` (the library failed inside; destroy the handles the call used) |
| 4 to 10 | Bad input | `DEFORMABLE_STATUS_INDEX_OUT_OF_RANGE`, `DEFORMABLE_STATUS_LENGTH_MISMATCH`, `DEFORMABLE_STATUS_NON_FINITE_VALUE`, `DEFORMABLE_STATUS_UNKNOWN_OBJECT` |
| 11 to 17 | Scene | `DEFORMABLE_STATUS_DEGENERATE_TETRAHEDRON_INVERTED`, `DEFORMABLE_STATUS_SCALE_OUT_OF_RANGE`, `DEFORMABLE_STATUS_TIME_WENT_BACKWARDS` |
| 18, 19 | Long tools | `DEFORMABLE_STATUS_CANCELLED`, `DEFORMABLE_STATUS_OUTPUT_TOO_LARGE` |
| 20 to 42 | Mesh tools and surface preparation | `DEFORMABLE_STATUS_NON_CLOSED_BOUNDARY` (triangulate), `DEFORMABLE_STATUS_INVALID_CAGE` (tetrahedralize), `DEFORMABLE_STATUS_NON_POSITIVE_THICKNESS` (extrude), `DEFORMABLE_STATUS_NO_CELLS` (splinters from an image) |
| 43 | Render surfaces | `DEFORMABLE_STATUS_SINGULAR_TRANSFORM` |
| 44 to 48 | License | `DEFORMABLE_STATUS_TETRAHEDRON_LIMIT_EXCEEDED`, `DEFORMABLE_STATUS_LICENSE_KEY_REJECTED`, `DEFORMABLE_STATUS_LICENSE_SIGN_IN_FAILED`; see [License statuses](#license-statuses) |

The statuses about one element fill the indices of `DeformableErrorDetails`:

| Status | `first_index` | `second_index` |
|---|---|---|
| `DEFORMABLE_STATUS_DEGENERATE_TETRAHEDRON_TOO_SMALL`, `_FLAT`, `_INVERTED` | The tetrahedron | |
| `DEFORMABLE_STATUS_DEGENERATE_REGION` | The material region | The polygon |
| `DEFORMABLE_STATUS_INDEX_OUT_OF_RANGE` from `deformable_triangulate` or `deformable_autocage`, `DEFORMABLE_STATUS_DEGENERATE_POLYGON` | The polygon | |
| `DEFORMABLE_STATUS_NON_MANIFOLD_EDGE`, `DEFORMABLE_STATUS_NON_CLOSED_BOUNDARY` | The edge's first vertex | The edge's second vertex |
| `DEFORMABLE_STATUS_UNKNOWN_VERTEX`, `DEFORMABLE_STATUS_DUPLICATE_VERTEX`, `DEFORMABLE_STATUS_DEGENERATE_FACE` | The face | |
| `DEFORMABLE_STATUS_MULTIPLE_BOUNDARIES`, `DEFORMABLE_STATUS_NULL_NORMAL` | The vertex | |
| `DEFORMABLE_STATUS_TETRAHEDRON_LIMIT_EXCEEDED` | The tetrahedrons the scene would simulate with the object (enabled objects) | The limit, 2,500 |

### License statuses

Nothing ever refuses to run. Without a subscription or a license, Deformable runs as Free, and a scene simulates up
to 2,500 tetrahedrons. The license is the Application license key the program activated, or else Free, the Standalone
subscription or the Standalone license of this device. `deformable_last_error_message` gives a license status's
message written to show the user as it is, such as **Free: this would simulate 3,120 tetrahedrons; the limit is 2,500
per scene**.

| Status | When |
|---|---|
| `DEFORMABLE_STATUS_TETRAHEDRON_LIMIT_EXCEEDED` (44) | On Free, `deformable_scene_add_object` would take the scene past 2,500 tetrahedrons; a disabled object does not count. It adds nothing then, and the scene goes on with the objects it holds. |
| `DEFORMABLE_STATUS_LICENSE_SERVICE_UNAVAILABLE` (45) | A `deformable_license_` call that goes online could not reach our licensing service or it did not answer, its answer did not verify, the device's clock contradicts it, or `deformable_license_set_online_access(0)` turned contacts off. Or `deformable_license_deactivate` or `_sign_out` could not free the seat: the license or sign-in is forgotten all the same. |
| `DEFORMABLE_STATUS_LICENSE_KEY_REJECTED` (46) | Our licensing service refused the Standalone key: it does not exist, was revoked or refunded, is not for Deformable, every seat of the license is in use, or this device was removed. Or the Application key was refused: it was revoked, its trial ended, its updates ended before this version was released, or the program is Blender or Maya, where Application licenses do not work. |
| `DEFORMABLE_STATUS_LICENSE_STORAGE_FAILED` (47) | The license state could not be saved in your user folder. The message names the folder. |
| `DEFORMABLE_STATUS_LICENSE_SIGN_IN_FAILED` (48) | `deformable_license_wait_for_sign_in` ended the sign-in: it was denied, or its code is no longer valid. Or this version of Deformable cannot sign in, or our licensing service could not read its request. Start a new sign-in, or update Deformable. |

`deformable_scene_add_object` is the only engine call the license can refuse. The mesh tools and the render surface
calls have no limit. When a scene holds more than fits, such as after a subscription or a Standalone license went too
long offline, `deformable_scene_step` simulates the objects that fit, in the order they were added, and holds the rest
still until a subscription or a license applies again. Creating, setting, reading and destroying never check the
license, so your program can always clean up. The `deformable_license_` functions read and change the license state: see
[License](https://help.tangerina.io/deformable/v0.6.0/user-guides/c/getting-started/#license).

## What the library checks, and what it cannot

The library checks every pointer for `NULL` and for alignment before it reads it, and it checks every value it
reads: indices, counts against each other, enumeration codes and NaN. When the library hits an internal failure, the
call returns `DEFORMABLE_STATUS_PANICKED` instead of crashing your program.

Some things only you can make sure of. Breaking one of these rules is undefined behaviour:

- Every handle you pass is live: created and not yet destroyed.
- Every count matches the memory its pointer points to.
- You never use a lent array after the event that ends it, and you never free one.
- Two threads never call into the same scene at the same time.

## Threads

| Item | From several threads |
|---|---|
| `DeformableScene` | It may move between threads, but it takes one call at a time. Lock it yourself if two threads share it. |
| Tools, such as `deformable_tetrahedralize` | Yes. They have no global state, so separate calls run at the same time. |
| `DeformableSurfaceEmbedding` | Yes. Reading and skinning never change it. Give each thread its own `DeformableDeformedSurface`. |
| `DeformableCancelFlag` | Yes. Every call on it is thread-safe. |
| The `deformable_license_` functions | Yes. One contact with our licensing service runs per process at a time; a second caller waits for it. |
| The last error | It is per thread. Read it on the thread that made the failed call. |

`deformable_scene_step` runs its own worker threads. By default it uses as many as the CPU offers, up to 16.
`deformable_scene_set_worker_count` changes the count. The results are the same for every count: the same
inputs and calls give bitwise identical results, run to run, on the same build.

### Cancel a long call

The tools whose cost grows with a size parameter take a `const DeformableCancelFlag *`: `deformable_triangulate`,
`deformable_tetrahedralize` and `deformable_autocage`. So does `deformable_scene_step`. Pass `NULL` when you do
not need to cancel.

Create a flag with `deformable_cancel_flag_create`. Another thread sets it with `deformable_cancel_flag_set(flag, 1)`,
and the call stops at its next check. A tool then returns `DEFORMABLE_STATUS_CANCELLED`. A step returns
`DEFORMABLE_STATUS_OK` with the outcome `DEFORMABLE_STEP_OUTCOME_CANCELLED` instead; see
[Scene](https://help.tangerina.io/deformable/v0.6.0/user-guides/c/scene/#cancel-a-step). The flag stays set until you clear it with
`deformable_cancel_flag_set(flag, 0)`. `deformable_cancel_flag_is_set` reads it.

This program runs `deformable_tetrahedralize` on a worker thread and cancels it from the main thread. Link it with
`-lpthread`:

```c
#include <pthread.h>
#include <stdio.h>

#include "deformable.h"

typedef struct Job {
    const DeformableCancelFlag *cancel;
    DeformableStatus status;
} Job;

/* Fills a unit cube with very small tetrahedrons: a long call. */
static void *tetrahedralize_cube(void *argument) {
    Job *job = argument;
    DeformableVector3 corners[8];
    for (int corner = 0; corner < 8; ++corner) {
        corners[corner].x = (double)(corner & 1);
        corners[corner].y = (double)((corner >> 1) & 1);
        corners[corner].z = (double)(corner >> 2);
    }
    const uint32_t triangles[12][3] = {
        {0, 2, 3}, {0, 3, 1}, {4, 5, 7}, {4, 7, 6}, {0, 1, 5}, {0, 5, 4},
        {2, 6, 7}, {2, 7, 3}, {0, 4, 6}, {0, 6, 2}, {1, 3, 7}, {1, 7, 5},
    };
    DeformableTriangleMeshView cage = {corners, 8, triangles, 12};
    DeformableTetrahedralizeParameters parameters = {0};
    parameters.maximum_edge_length = 0.01;
    deformable_anisotropy_default(&parameters.anisotropy[0]);
    deformable_anisotropy_default(&parameters.anisotropy[1]);

    DeformableTetrahedralization *result = NULL;
    job->status = deformable_tetrahedralize(&cage, &parameters, job->cancel, &result);
    if (job->status != DEFORMABLE_STATUS_OK) {
        /* The last error belongs to this thread: read it here. */
        fprintf(stderr, "worker: %s\n", deformable_last_error_message());
    }
    deformable_tetrahedralization_destroy(result); /* NULL when the call failed. */
    return NULL;
}

int main(void) {
    DeformableCancelFlag *cancel = NULL;
    deformable_cancel_flag_create(&cancel);

    Job job = {cancel, DEFORMABLE_STATUS_OK};
    pthread_t worker;
    pthread_create(&worker, NULL, tetrahedralize_cube, &job);

    /* The user pressed Cancel: set the flag from this thread. */
    deformable_cancel_flag_set(cancel, 1);

    pthread_join(worker, NULL);
    printf("cancelled: %s\n", job.status == DEFORMABLE_STATUS_CANCELLED ? "yes" : "no");
    deformable_cancel_flag_destroy(cancel);
    return 0;
}
```

```text
worker: cancelled
cancelled: yes
```

Destroy a cancel flag only when no call, on any thread, still uses it.

## Next steps

- [Getting started](https://help.tangerina.io/deformable/v0.6.0/user-guides/c/getting-started/): build the library and link a program.
- [Status codes](https://help.tangerina.io/deformable/v0.6.0/api-references/c/errors/#deformablestatus): every `DEFORMABLE_STATUS_` code.
- [Errors](https://help.tangerina.io/deformable/v0.6.0/api-references/c/errors/): the last-error functions and the version.
- [Cancel flags](https://help.tangerina.io/deformable/v0.6.0/api-references/c/errors/#deformablecancelflag): the cancel flag handle and its functions.
