How the reserved memory works for a string in C

1

I had a doubt about the chains in C, in this the chains are an array of chars but the way to work with them is to save only the memory address of the first character, thus advancing in the memory address, considers that the string terminated when a null character is found. So far this is what I understand of the chains but my question is:

If the only reference I have from the string is its first character when doing

free(myString)

(this being a char* containing a string) Would only release the memory of the first character? Should I free all the characters in the string?

    
asked by Cristofer Fuentes 14.05.2017 в 23:52
source

1 answer

3

If you had a doubt, then you no longer have it, no?

Well, the strings in C are nothing more than pointers to the character ( char * ) as you mention they are a particular type of vectors, which like their name says are char vectors, with the particularity that they have a mark at the end of the (the character '\ 0') ( Wikibooks ) .

Let's start with the basics:

A pointer is a memory address pointing to another direction that contains a value, that being said, we have the following:

+---+---+---+---+---+---+---+---+---+---+---+----+
| N | H | O | L | A |   | M | U | N | D | O | \n | <- Contenido de la memoria
+---+---+---+---+---+---+---+---+---+---+---+----+
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A |  B | <- Posición de memoria
+---+---+---+---+---+---+---+---+---+---+---+----+ 

[0] es NULL.

This is how memory works in C, after this, what you mention:

  

Would it only release the memory of the first character?

The answer is simply NO , consider the following example:

char *test = malloc(11); // Se piden 11 bytes de forma dinámica.
// Haz lo que sea con el "string"
free(test); // Se libera toda la memoria.

In the call to free(void *); the entire requested memory block is deleted using malloc(size_t); , because the standard C library knows how to manage the memory, but it leaves you with the option of how much memory you need, the just ask the operating system.

Calls to free only release reserved memory dynamically, so if you do the following:

char *test2 = "Hola Mundo\n";
free(test2); // ERROR!

And regarding your second question:

  

should I free all the characters in the string?

Again, NO ! And just by giving the first memory address to free(void *) the function knows each and every one of the elements that make up the pointer, that is, its size.

Normally if you ask malloc to put 10 bytes for your use, malloc can place 11 or 12 as you want, to know something called "pointer tag" , which is what you know all the pointer information that returns the function, but most platforms are sufficiently "smart" to give you the pointer to virtual memory, which is not so easy to lose.

    
answered by 15.05.2017 / 00:33
source