Strings as pointers in c

I'm learning C and I perfectly understand pointers and their relationship to arrays, but my problem comes with strings. I know to declare a string like this:

char cadena[] = "Hola";

Is equivalent to:

char cadena[] = {'H','o','l','a','\0'}

And that therefore if you want a function to return a string of characters you have to make it static so that the memory address is valid outside the scope of the function:

char *getCadena (){
    static char cadena[] = "Hola"; //static para que su dirección en la memoria sea global
    return cadena;
}

What Not I understand is that it does the compiler when you declare the string like this:

char *cadena = "Hola";

Declare the array as static? I'm asking because when testing it I've seen that even declaring a string like that mode inside a function can be returned without problems, so the address has to be global anyway:

char *getCadena (){
char *cadena= "Hola";
return cadena;
}

Thanks in advance and a greeting

 5
Author: rmac, 2016-08-25

1 answers

Static allocation

What I don't understand is that the compiler does when you declare the string like this:

char *cadena = "Hola";

The compiler creates the literal " Hello "in a read-only area of memory and cadena points to that address, i.e.: it is the pointer cadena that is in the Stack, not the literal"Hello". When you return, you return the address of the literal (where it pointed cadena) and therefore it is safe to return.

The use of static creates a difference, because the variable that would normally remain in the stack, is actually in static memory. This has another use case, it is for when a function needs to store a state between different calls.

Automatic allocation

Now when you do...

char cadena[] = "Hola";

Creates the literal "Hello" in a read-only area of memory, but when the function is invoked copies the literal to the string array that is allocated in the stack.

Here is another difference, the latter can be modified as long as its maximum length is not changed. Well, it's a copy.

It is not safe to retronate the address of this array as the entire string is in the Stack.

Dynamic Allocation

There is another way to allocate memory in c, it is by using malloc and free which are used respectively to reserve memory and release a pre-reserve.

This type of allocation is done in the Heap, bone dynamic memory.

This type of allocations are safe to return from a function, but you should not forget to release it (with free) because otherwise the program will end up using all the memory and will stop by out_of_memory

 6
Author: rnrneverdies, 2020-06-11 10:54:57