Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

memory ownership and copies — concept C23

C requires explicit ownership: an automatic object lives to block exit, a static object for the program, and a dynamic allocation from successful allocation to exactly one `free`. Copying bytes does not copy resources referenced by fields, overlapping regions require `memmove`, and use-after-free, double free, or access outside an object is undefined.

Version: C23

Syntax

memory ownership and copies

C requires explicit ownership: an automatic object lives to block exit, a static object for the program, and a dynamic allocation from successful allocation to exactly one free. Copying bytes does not copy resources referenced by fields, overlapping regions require memmove, and use-after-free, double free, or access outside an object is undefined.

For every dynamic object, state which function creates it, who may transfer ownership, and which function releases it. A constructor should either return a fully ready object or clean up partial fields; a destroy function may accept NULL only when its contract says so.

Before malloc(count * size), check count <= SIZE_MAX / size. In C23, realloc(ptr, 0) with non-null ptr has undefined behavior; use free(ptr) to release it. After free, clearing one pointer copy does not invalidate its other aliases.

pointer arithmetic is defined only within the same array object (a non-array object behaves as an array of length one for this rule) and at the one-past position. array object bounds permit forming a one-past pointer and using it as a sentinel, but never dereferencing it; arithmetic beyond that bound has undefined behavior. Pointer subtraction requires both pointers to designate the same array object and the mathematical result to fit in ptrdiff_t.

Examples

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) { char *copy = malloc(6); if (!copy) return 1; memcpy(copy, "CKTIS", 6); puts(copy); free(copy); return 0; }

Result

CKTIS

C requires explicit ownership: an automatic object lives to block exit, a static object for the program, and a dynamic allocation from successful allocation to exactly one `free`. Copying bytes does not copy resources referenced by fields, overlapping regions require `memmove`, and use-after-free, double free, or access outside an object is undefined.

Sources