3

If I want to allocate memory in function:

char* allocate() {
    char *cp = (char*)malloc(10);
    ...
    return cp;
}

can I use the returned content in cp from main()? and how to free cp?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
legend0011
  • 139
  • 7

3 Answers3

5

can I use the returned content in cp in main()?

Yes, you can.

and how to free cp?

Using

free(cp); // Replace cp with the name of the pointer if you are using it in another function


Also, you should not cast the result of malloc(and family) in C
Community
  • 1
  • 1
Spikatrix
  • 20,225
  • 7
  • 37
  • 83
  • but how can user of main know the char* is allocated dynamicly?? and if he didn't check the code of function, there will be memory leak???? – legend0011 Apr 29 '15 at 09:42
  • @legend0011 , If the user did not free the allocated memory by `malloc`, then there will be a memory leak. Yes, you could do this with `strdup`. `strdup` is `malloc`+`strcpy` , nothing else. – Spikatrix Apr 29 '15 at 09:46
  • 1
    @legend0011 : the calling code should NOT know whether the memory was allocated dynamically or not. Instead, you create a corresponding `deallocate` function for your `allocate` function, that the calling code has to call. This `deallocate` function does a `free` and/or whatever else is required to de-allocate the object. – Sander De Dycker Apr 29 '15 at 10:00
  • 1
    In a language like C, sometimes it's a matter of documenting the functions, e.g. Returned pointers should be freed, and trusting the caller to read the docs. As Sander De Dycker says, sometimes you can help by making as part of an alloc/dealloc set of functions, but often you need to return >1 result, in which case there's not the pairing and you loose that 'hint' to the user anyway. – Gwyn Evans Apr 29 '15 at 10:12
2

You should always test against failure of malloc(3), so at least use perror(3) & exit(3) like:

  char *cp = malloc(10);
  if (!cp) { perror("malloc"); exit(EXIT_FAILURE); };

Some Linux systems are enabling memory overcommit. This is a dirty feature that you should disable.

If you are coding seriously (e.g. a robust library to be used by others) you may need to provide more sophisticated out-of-memory error recovery (perhaps having a convention that every allocating routine could return NULL on failure). YMMV.

Indeed, at some later point you need to call free(3) with the pointer in cp. If you don't you'll have a memory leak. After that you are not allowed to use i.e. dereference that pointer (be careful about pointer aliases) or simply compare it against some other pointer; it would be undefined behavior.

It is important to have a convention about when and who should call free. You should document that convention. Defining and implementing such conventions is not always easy.

On Linux you have quite useful tools to help about C dynamic memory allocation : valgrind, passing -Wall -Wextra -g (to get all warnings and debug info) to the GCC compiler, passing -fsanitize=address to a recent gcc, etc.

Read also about garbage collection; at least to get some terminology, like reference counting. In some C applications, you might later want to use Boehm's conservative GC.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • Hmm, I've not done so, but I'm very tempted to down-vote just for the 'at least use perror(3) & exit(3)', having been hit by library function writers who thought that was a good idea when their library function had a problem. – Gwyn Evans Apr 29 '15 at 10:19
  • @GwynEvans: having a library function doing `perror` than `exit` on out-of-memory condition is *often* acceptable, and certainly preferable to not checking result of `malloc` – Basile Starynkevitch Apr 29 '15 at 10:22
1

1. can I use the returned content in cp in main()?

Yes, you can. The scope and lifetime of dynamically allocated memory (on heap) is not limited to the function scope. It remains valid untill it is free()d.

Note: Always check for the success for malloc() and do not cast it's return value.

2. and how to free cp?

Once you've done using the memory, from main(), or from any other function, you can call free(<pointer>);, where <pointer> is the variable in which you had collected the return value of allocate().

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • 4
    _[This is third time, in a row today, i'm repeating myself :-)..]_ Dear downvoter, please leave a note mentioning the reson behind the downvote. Thank you. :-) – Sourav Ghosh Apr 29 '15 at 10:00