Phil Bouchard
Phil Bouchard

Reputation: 125

C functions requiring explicit call to free()

I would like to know all the C standard functions that uses malloc() internally and returns a pointer to the newly allocated block of memory. AFAIK there is:

Is that it? I am writing a complex parser that will change all C raw pointers to more elaborate C++ smart pointers and I need to know where this can't be done automatically.

Upvotes: 2

Views: 372

Answers (3)

Your list is rather correct, but strdup and getcwd is POSIX (not standardized in C99), and get_current_dir_name is GNU (not even POSIX).

You'll find other functions returning some heap-allocated data.

But you always should read the documentation of some function before using it. It will tell you if the returned value is heap allocated (and who and how should it be released).

Some functions take an address of pointer and might change it. For example getline(3) (POSIX) or asprintf(3) or open_memstream(3) (and some allocation could even happen later).

BTW some standard functions like fopen are probably using heap-allocated memory (which get freed at fclose time).

Likewise, for your own libraries, document them well enough to tell notably who is responsible of free-in g (or destroying otherwise) every heap-allocated pointer. Even for your own private functions, document that in comments.

Automatizing the detection of functions related to dynamic heap memory allocation is difficult and could be impossible to do reliably in the general case (see Rice's theorem), so makes an interesting research project.

Upvotes: 1

melpomene
melpomene

Reputation: 85887

The list is:

  • malloc
  • calloc
  • realloc
  • aligned_alloc (new in C11)

None of the functions you listed are standard C.

Upvotes: 5

gsamaras
gsamaras

Reputation: 73444

  1. void* malloc (size_t size);

Allocates a block of size bytes of memory, returning a pointer to the beginning of the block.

  1. void* realloc (void* ptr, size_t size);

Changes the size of the memory block pointed to by ptr.

  1. void* calloc (size_t num, size_t size);

Allocates a block of memory for an array of num elements, each of them size bytes long, and initializes all its bits to zero.

Upvotes: 1

Related Questions