Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should this C pointer be released?

Tags:

c

memory

Please excuse my C newbiness.

Consider the following C procedure:

int doSomething() {
    char *numbers="123456";
    ...
}

Before this procedure exits should I be releasing the 'numbers' pointer?

like image 878
rmcc Avatar asked Dec 01 '22 05:12

rmcc


2 Answers

No, you didn't malloc it. Why should you release it?

Often, the string is placed in a read only section of the executable.

like image 85
mmx Avatar answered Dec 22 '22 01:12

mmx


In C language you don't and can't "release" pointers. Pointers are ordinary scalar variables. There's nothing you can do with them in terms of "releasing" or anything like that.

What one can be "releasing" is the memory a pointer is pointing to. But in C you only have to release memory that was explicitly allocated by malloc/calloc/realloc. Such memory is released by calling free.

Note again, that in your program you might have several (a hundred) pointers pointing to the same block of allocated memory. Eventually, you'll have to release that memory block. But regardless of how many pointers you have pointing to that block, you have to release that memory block exactly once. It is your responsibility to make sure that you release it. And it is your responsibility to make sure you released it exactly once. I'm telling you this just to illustrate the fact that what you release is the memory block, not the pointers.

In your example, your pointer points to a memory block that was never allocated by any of the aforementioned functions. This immediately means that you don't need to release anything.

like image 28
AnT Avatar answered Dec 22 '22 03:12

AnT