Thread: allocation responsibility

  1. #1
    Registered User
    Join Date
    Nov 2010
    Posts
    7

    allocation responsibility

    Lets say I want to create a function which load a file and return a string which contain it's content.
    the signature is:
    char* load_file(char* filename);

    the problem is that I'm using 'malloc' inside my function - and I'm putting the client of this function to be responsible for 'free' the allocated space.
    How should i do it right?
    thanks in advance,
    itay

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    You could simply require that the caller free the memory. Alternatively, you could provide another function, currently a simple wrapper for free, that must be used to free the memory. This gives you more leeway for change in the future.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Nov 2010
    Posts
    7
    Quote Originally Posted by laserlight View Post
    You could simply require that the caller free the memory. Alternatively, you could provide another function, currently a simple wrapper for free, that must be used to free the memory. This gives you more leeway for change in the future.
    it's still doesn't look reasonable to me. if i supply such interface, all i can do is to write in a comment for the user such as "this is your respons. to free the...".
    I heard a bout aמ approach which take as a parameter pointer for the return value, and then - somehow is understandable that the user is responsible.
    is there any definition or official example where i can learn about that.
    by the way, i don't see the different if using wrapper.. still, my client want a string with the file content and i cannot predict the size...

    thanks again

  4. #4
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by ItayB View Post
    it's still doesn't look reasonable to me. if i supply such interface, all i can do is to write in a comment for the user such as "this is your respons. to free the...".
    I heard a bout aמ approach which take as a parameter pointer for the return value, and then - somehow is understandable that the user is responsible.
    is there any definition or official example where i can learn about that.
    by the way, i don't see the different if using wrapper.. still, my client want a string with the file content and i cannot predict the size...

    thanks again
    Nope... *never* put such a task in user hands. They won't do it.

    What Laserlight was saying (I thnk) is that it's not wrong to malloc memory inside a function and return a pointer that is to be freed in some other part of the program. It's not ideal, but it is done rather a lot. It's probably better to malloc the memory outside the function, pass in a pointer. That way malloc and free exist on the same operational level in your code.

    It's not a big issue... Just so you do actually free the memory.

  5. #5
    Registered User
    Join Date
    Nov 2010
    Posts
    7
    Quote Originally Posted by CommonTater View Post
    Nope... *never* put such a task in user hands. They won't do it.

    What Laserlight was saying (I thnk) is that it's not wrong to malloc memory inside a function and return a pointer that is to be freed in some other part of the program. It's not ideal, but it is done rather a lot. It's probably better to malloc the memory outside the function, pass in a pointer. That way malloc and free exist on the same operational level in your code.

    It's not a big issue... Just so you do actually free the memory.
    Thanks for your answer. you define it better by saying: "same operational level in your code".
    lets speak about the String.h in C. when i use strcpy or substr, as a client, i m expecting to get new string in both function. but the implementation (as i guessing) doesn't contain malloc in it... so.. what is the point with those functions? are they expecting from me to malloc a place first and then call these functions?

  6. #6
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by ItayB View Post
    Thanks for your answer. you define it better by saying: "same operational level in your code".
    lets speak about the String.h in C. when i use strcpy or substr, as a client, i m expecting to get new string in both function. but the implementation (as i guessing) doesn't contain malloc in it... so.. what is the point with those functions? are they expecting from me to malloc a place first and then call these functions?
    Yes they are... all functions in C require you to "give them a place to land" so to speak. It would be a terrible error to assume that every time you copy a string you want to create a new string buffer. That is why they all ask for both destination and source pointers.

    C is an extremly literal and unassuming language. It doesn't do anything you don't tell it to do... But think about that... isn't that how it should be?

  7. #7
    Registered User
    Join Date
    Nov 2010
    Posts
    7
    Quote Originally Posted by CommonTater View Post
    Yes they are... all functions in C require you to "give them a place to land" so to speak. It would be a terrible error to assume that every time you copy a string you want to create a new string buffer. That is why they all ask for both destination and source pointers.

    C is an extremly literal and unassuming language. It doesn't do anything you don't tell it to do... But think about that... isn't that how it should be?
    so... if we go back to my function (getting filename and return it content inside a string).
    should i create another function like:
    int getFileSize(char* filename);
    which return the size of the string (that the user should create for the next function)?

  8. #8
    Registered User
    Join Date
    Nov 2010
    Posts
    7
    look at the strtok example here: strtok() - Standard C String & Character - C Programming Reference - eLook.org
    where the 'result' save its content? can u explain why it is legal?

  9. #9
    Registered User
    Join Date
    Jan 2009
    Posts
    1,485
    Why do you think it would not be legal? Result, does not really save the content but the address in the string. Think of it as an offset in the string.

  10. #10
    Registered User
    Join Date
    Nov 2010
    Posts
    7
    Quote Originally Posted by Subsonics View Post
    Why do you think it would not be legal? Result, does not really save the content but the address in the string. Think of it as an offset in the string.
    so, should i assume that the function strtok call to malloc? and i should call free(result)?

  11. #11
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Quote Originally Posted by ItayB View Post
    look at the strtok example here: strtok() - Standard C String & Character - C Programming Reference - eLook.org
    where the 'result' save its content? can u explain why it is legal?
    Result doesn't really save content. The strtok function just uses a static pointer to keep track of it's place in the original string, and is able to return to you a chunk of your string. To do this, it edits your string instead of using new memory. If you needed the original string you should have passed a copy.

    Also what laserlight was saying here

    Quote Originally Posted by laserlight View Post
    You could simply require that the caller free the memory. Alternatively, you could provide another function, currently a simple wrapper for free, that must be used to free the memory. This gives you more leeway for change in the future.
    is that an abstraction of the free function would be reasonable. In the context of a file library, pairs of functions like OpenFile() and CloseFile() make sense. It is provided as a convenience; otherwise, you would have to remember what CloseFile() does and do that every time.

  12. #12
    Registered User
    Join Date
    Jan 2009
    Posts
    1,485
    Quote Originally Posted by ItayB View Post
    so, should i assume that the function strtok call to malloc? and i should call free(result)?
    No, you could create something similar yourself like this.

    Code:
    char *str = "hello";
    char *pt = str;
    
    puts(pt);
    pt++;   
    puts(pt);

  13. #13
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by ItayB
    by the way, i don't see the different if using wrapper.. still, my client want a string with the file content and i cannot predict the size...
    whiteflags has elaborated on this in post #11, but on my assertion that "this gives you more leeway for change in the future": suppose later it turns out that you want to say, use your own memory pool, or otherwise not use malloc. Your load_file function will change, and the caller should no longer use free. If you provided a corresponding free function of your own, you can just change that function's implementation accordingly, and the user's code can remain the same.

    Quote Originally Posted by CommonTater
    Nope... *never* put such a task in user hands. They won't do it.
    That is why I like RAII. However, this is C. If they won't do it, it is their memory leak. Too bad.

    Quote Originally Posted by ItayB
    so, should i assume that the function strtok call to malloc? and i should call free(result)?
    No. Instead of strtok, I suggest looking at a simpler example, e.g., strcpy. strcpy is not concerned with how the memory it uses is obtained. You could use malloc, you could use arrays local to a function, you could use arrays with static storage duration... but the end result of copying a string is the same as long as you use strcpy correctly. In other words, strcpy leaves the specifics of allocating and deallocating memory to the user of the standard library.

    Now, consider malloc. It is likely to be implemented using some lower level OS specific functions. Yet, you are not required to use any OS specific function to free the memory that malloc allocates. Rather, you would reach for the free function. In other words, malloc and free are concerned about the specifics of allocating and deallocating memory, respectively.

    This is the lesson here: if you need to be concerned about the specifics of allocating the resource, then be concerned about the specifics of deallocating the resource, i.e., you also provide a deallocation function that you require users to call (if they forget, that's their business). Otherwise, you leave the specifics of both allocating and deallocating to the user. If you are concerned about the specifics of allocating the resource but leave the specifics of deallocating the resource to the user, then you cannot easily change the specifics of allocating the resource without potentially breaking the user's code (besides making life tougher for users of your library).
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  14. #14
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by ItayB View Post
    so... if we go back to my function (getting filename and return it content inside a string).
    should i create another function like:
    int getFileSize(char* filename);
    which return the size of the string (that the user should create for the next function)?
    If you need to know the length of the string use strlen()... in general use there should be no need to create a function for a function that already exists.

    If you need to know the size of the file on disk, that's a different matter. Here you may need to assign a memory buffer to load the file contents into.

  15. #15
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by laserlight View Post
    That is why I like RAII. However, this is C. If they won't do it, it is their memory leak. Too bad.
    Laserlight... when I say "user" I mean the person sitting "between keyboard and chair" staring at the wonderful craft of your work... (It appears that you are using "user" to indicate the programmer writing the code.)

    My suggestion that it would be irresponsible to put something a critical as allocating or releasing memory for a program in a user's hands is that it fails to consider the impact upon other tasks running in a multitasking environment.

    If there is one thing 35+ years in electronic service has taught me it is very simply that if there is a way for a human being to screw something up... they'll do it. Then, of course, they'll deny it.

    Software should never ask questions like "How much memory do you want" or "Do you want to disable this device". These dangerous decisions should be made at run time by software written to take the circumstances into consideration.
    Last edited by CommonTater; 11-12-2010 at 02:13 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem with custom dynamic memory allocation routines
    By BLauritson in forum C++ Programming
    Replies: 12
    Last Post: 03-11-2010, 07:26 AM
  2. Dynamic array Allocation
    By deepak_j in forum C Programming
    Replies: 3
    Last Post: 08-17-2009, 07:18 AM
  3. dynamic allocation from 1 instead of zero
    By cfdprogrammer in forum C Programming
    Replies: 27
    Last Post: 04-28-2009, 08:21 AM
  4. pointer to array with dynamic allocation
    By cfdprogrammer in forum C Programming
    Replies: 22
    Last Post: 04-07-2009, 09:56 AM
  5. redundant allocation
    By George2 in forum C++ Programming
    Replies: 22
    Last Post: 03-06-2008, 06:43 PM