Calloc inside function

Looking at this question that has just been asked: would doing something like this be considered bad practice, then?

char* strpart(char* string, int start, int count) { char* strtemp; int i = 0; int j = 0; int strL = strlen(string); if ( count == 0 ) { count = strL; } strtemp = (char*) calloc((count + 1), sizeof(char)); for ( i = start; i < (start+count); i++ ) { strtemp[j] = string[i]; j++; } return strtemp; }

Sorry it's written quickly, but the basic principle is - when NOT using a static buffer inside a function is it bad practice to assign memory inside a function? I assume so because it wouldn't be freed, would it? Thought I ought to ask though.

-------------Problems Reply------------

It's not bad pratice but it can easily create memory leaks (the callers have to remember to free the memory).

One thing I like to do is use a naming convention to indicate what functions can allocate. For example, I'd name that function:

char* strpart_alloc(char* string, int start, int count)

It's always OK practice to allocate memory dynamically inside a function PROVIDED you return a pointer to that memory to the outside world, so that something else can free it, or free it yourself within the function.

Well, it's dangerous. I'd try to avoid it when possible.

Your assumption is correct - the memory will not get released automatically.

The problem is that the return value here is memory allocated on the heap, the caller of your function has to remember to free. You're allocating memory here that will not (by you) get released. It's always a bad idea to put constraints on the user of your API.

Sometimes (rarely) this can't be avoided, so if you do this, make sure to document it very clearly.

It's common to do this. You just have to clearly note in your documentation "API" that it is the caller's responsibility to free the returned pointer when finished.

It is not a bad practice. The fact that the function returns a malloc-ed (or calloc-ed) memory becomes a part of its external specification. It becomes a the caller's responsibility to free it when it is no longer necessary.

It is inelegant though. It is inelegant since it 1) forces the use of dynamic memory, when the caller might prefer to avoid it, and 2) forces the use a specific kind of dynamic memory - the malloc-ed one, when the caller might prefer to use its own allocation mechanism.

Category:c# Views:1 Time:2010-02-09

Related post

  • Dynamically create variables inside function 2008-09-23

    I want to create variables inside function from dictionary. Lets say I have a dictionary bar = {'a': 1, 'b': 2, 'c': 3} and function def foo(): pass What I want to do is to create inside function "foo" variables with names of each dictionary item nam

  • String literals inside functions: automatic variables or allocated in heap? 2008-10-06

    Are the string literals we use inside functions automatic variables? Or are they allocated in heap which we have to free manually? I've a situation like the code shown below wherein I'm assigning a string literal to a private field of the class (mark

  • Is it pythonic to import inside functions? 2009-06-21

    PEP 8 says: Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants. On occation, I violate PEP 8. Some times I import stuff inside functions. As a general rule, I do this

  • Running exec inside function 2010-04-13

    How can you use the python exec keyword inside functions? --------------Solutions------------- It's going to damage your function's performance, as well as its maintainability, but if you really want to make your own code so much worse, Python gives

  • Why inner "template" class not allowed inside function? 2010-08-10

    Reading C++ Templates: The Complete Guide and it says Note that templates cannot be declared in a function It does not give explanation and/or cross reference to any other chapter in the book or external resource. Could someone help in explaining thi

  • How to "interleave" C/C++ souce with my string (only inside functions at appropriate places)? 2010-10-21

    For example, there is the source: void func1() { func3(); if(qqq) { func2(); } func4( ); } It should be transformed to: void func1() { MYMACRO func3(); MYMACRO if(qqq) { MYMACRO func2(); MYMACRO } MYMACRO func4( ); MYMACRO } I.e. to insert "MYMACRO\n

  • function inside function 2011-01-28

    Simple example. Two methods, one called from another: def method_a(arg): some_data = method_b(arg) def method_b(arg): return some_data In python we can declare def inside another def. So, if method_b required and called only from method_a, should i d

  • Motion Tween Doesn't Work Inside Function in ActionScript 3 and Flash CS5 2011-02-11

    i have a problem with putting a motion tween in function. my code works perfectly in CS4(but unfortunatly flash CS4 hangs all the time on my PC. whoever in CS5 the motion works fine outside function but when i put it inside a function it behave stran

  • what is diffrence using var or this inside function in JS? 2011-03-05

    I wonder is there any diffrence, in below codes: function x(){ var a = 1; } and: function x(){ this.a = 1; } --------------Solutions------------- The first creates a locally-scoped variable, which will not be retained after the function exits (unless

  • Object initialization problem - not null inside function but is null when I exit function 2011-03-25

    I have code like this ( I have used Dojo for classes ): var current_div=null; var current_element=null; var elements_container=null; var status_container=null; function main(){ //alert(status_container==null); load_status_system(); //alert(status_con

  • Is there any use case for class inside function after introduction of lambda? 2011-07-29

    From the wikipedia article about Lambda functions and expressions: users will often wish to define predicate functions near the place where they make the algorithm function call. The language has only one mechanism for this: the ability to define a c

  • Python, SimPy: Using yield inside functions 2011-11-28

    Helo, I'm building a relatively complex Discrete Event Simulation Model in SimPy. When I try to put my yield statements inside functions, my program doesn't seem to work. Below shows an example. import SimPy.SimulationTrace as Sim import random ## Mo

  • How to use a variable inside function in R 2012-02-18

    I'd like to use a variable in my function but I can't figure out how to do this. Here is my function and the call on a data.frame: errorByAleles <- function(values){ counts1 <-, stringsAsFactors = FALSE) modal_value1

  • How to call function inside function in C++ ? 2012-03-06

    Problem: Through C++ function I need to run thread function which in turn calls another Singleton C++ function . This called function will call C function (Which runs a infinite loop to change embedded system status in every 10 millisecond). Question

  • C++ Syntax error when declaring function inside function 2012-12-24

    I am trying to create a program that allows me to find the nth root of a number. I tried running this on xcode and, I get an error that prevents me from running it. I'm getting an error for this line: double f(double x) { In this line, I am trying to

  • Need to get the Post ID inside functions.php 2013-12-06

    I've been at this issue for HOURS now. I need some help or a push in the right direction at least, because I'm stumped. Issue: I need to get the post ID inside functions.php I'm using a plugin called SS Quiz. This plugin is a quiz making plugin, in w

  • Global variables of function inside function of a class 2014-06-20

    class Someclass{ function topFunction() { function makeMeGlobal($var) { global $a, $b; $a = "a".$var; $b = "b".$var; } makeMeGlobal(1); echo "$a <br>"; echo "$b <br>"; makeMeGlobal(2); echo "$a <br>"; echo "$b <br>"; } } I am

  • declaration inside function syntax 2012-01-04

    I am writing in C, not C++ or C# How can open additional array inside a function and put 0 in all its elements in one line only? at the moment i have errors Error 1 error C2065: 'new' : undeclared identifier Error 3 error C2143: syntax error : missin

  • Functions inside functions in C 2009-06-05

    I'm making a code that is similar to this: #include <stdio.h> double some_function( double x, double y) { double inner_function(double x) { // some code return x*x; } double z; z = inner_function(x); return z+y; } int main(void) { printf("%f\n"

Copyright (C), All Rights Reserved.

processed in 0.071 (s). 11 q(s)