Should this C pointer be released?

Please excuse my novelty C.

Consider the following procedure C:

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

Before I exit this procedure, should I send a pointer to the "number"?

+4
source share
7 answers

No, you do not malloc him. Why should you let him go?

Often a line is placed in a read-only section of an executable file.

+9
source

In C, you cannot and cannot release pointers. Pointers are ordinary scalar variables. There you can do nothing in terms of “liberation” or something like that.

What can be "freed" is the memory pointed to by the pointer. But in C, you need to free memory that has been explicitly allocated by malloc / calloc / realloc . Such memory is freed up when calling free .

Please note that in your program you may have several (hundreds) of pointers pointing to the same block of allocated memory. In the end, you will have to free this block of memory. But no matter how many pointers you point to this block, you need to free this block of memory exactly once. It is your responsibility to release it. And you are responsible for ensuring that you release it exactly once. I am telling you this simply to illustrate the fact that you are releasing a block of memory, not pointers.

In your example, your pointer points to a block of memory that has never been allocated by any of the above functions. This immediately means you don't have to let go of anything.

+4
source

No, there is no need to do this, and it is wrong (thanks dmckee). The character string will be in the binary data segment , so it cannot be freed. The memory was not dynamically allocated.

"numbers" will be on the stack, so it will disappear when the function returns.

+3
source

in fact, you do not need to call delete or free, these operators are only used to clear the memory that was allocated by my memory allocation during operation, for example malloc, calloc, GlobalAlloC, HeapAlloc, etc. When you define a pointer, as in the example, you are actually allocating space for the character array in the executable. therefore, the line size will be larger than the size of the executable file, which will increase your working set.

+2
source

Not; there is nothing to release. The string literal "123456" is an array of char (const char in C ++) with a static degree. The memory for it is allocated when the program starts and is saved until the program is released. All you have done is assign the address of the string literal numbers ; you didn’t actually allocate any memory.

+1
source

No, it points to the previously allocated memory in the process data segment. Only free(3) do you have malloc(2) -ed (modulo some library functions like getaddrinfo(3) / freeaddrinfo(3) .)

0
source

NO, since it was not allocated malloc / calloc / realloc.

It will be automatically "released" because it is an automatic variable.

0
source

Source: https://habr.com/ru/post/1310393/


All Articles