Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

char* as an argument to a function in C

Tags:

c

cstring

When passing a char* as an argument to a function, should the called function do a free on that string? Otherwise the data would be "lost" right and the program would leak data. Or are char* handled in a special way by the compiler to avoid everyone from having to do free all the time and automatically deletes it one it goes out of scope? I pass "the string" to the function so not an instance to an already existing char*. Or should one use char[] instead? Just feels so dumb to set a fixed limit to the argument input.

like image 635
inquam Avatar asked Nov 28 '22 10:11

inquam


2 Answers

Keep this simple principle in mind: "always free memory at the same level that you allocated it". In other words a function should never try to free memory that it itself has not allocated. A short example to clarify this:

#include "graphics.h"

// The graphics API will get a Canvas object for us. This may be newly allocated
// or one from a pool of pre-allocated objects. 
Canvas* canvas = graphics_get_canvas (); 

// If draw_image () frees canvas, that violates the above principle.
// The behavior of the program will be unspecified. So, just draw the image
// and return.
draw_image (canvas); 

// This is also a violation.
// free (canvas) ; 

// The right thing to do is to give back the Canvas object to the graphics API
// so that it is freed at the same 'level' where it was allocated. 
graphics_return_canvas (canvas);

Note that the function is not named graphics_free_canvas () or something like that, because the API may choose to free it or reuse it by returning it to a pool. The point is, it is an extremely bad programming practice to assume ownership of a resource that we did not create, unless we are specifically told otherwise.

like image 175
Vijay Mathew Avatar answered Dec 22 '22 09:12

Vijay Mathew


It sounds like you're asking about this usage:

void foo(char* str);
foo("test string");

This is a special case; "test string" is a constant string stored in the string table within the executable, and doesn't need to be freed. foo should actually take a const char* to illustrate that, and allowing string literals to be stored in non-constant char*s is deprecated in C++

like image 29
Michael Mrozek Avatar answered Dec 22 '22 10:12

Michael Mrozek