Doubts about the realloc function

Asked

Viewed 342 times

1

realloc realoca "negatively" the memory? That is, if the original size of a vector is greater than the value passed in the reallocation, the vector will be reduced?

For example, if I do this:

char *exemplo = calloc(256, sizeof(char)); 
strcpy(exemplo, "Teste"); 
exemplo = realloc(exemplo, 3 * sizeof(char)); 
printf("%s\n", exemplo);

Why do you keep printing "Test"? It’s as if the allocated space still remains...

  • Note: by definition sizeof (char) is 1.

2 answers

4


In C the space you reserve for the dasdos and how you effectively use this data are two separate things.

Since sizeof(char) is always 1, you in fact, when calling realloc left only 3 bytes reserved for your sample text - as you expected.

Only the "printf" function does not know this - when searching for a string for printing, as the control code "%s" it will print the entire target string until it finds a character \x00. If there is none before the end of the area allocated to astrign pdem happens one of two things: your program terminates with a segmentatin fault, or, pritnf consumes data from an area of an area where it may be being used for other things within your program. By awareness, the bytes you released with realloc remained within a segment used in your program and this data was not used by anything else - then your printf worked.

But the big lesson to have in memte is: in C there is no automatic mechanism that will "stop" the access to memory and restrict it to areas you have allocated (either with malloc, or reserving the dimensions in variable declaration) - You are responsible for knowing that all functions called by your program are accessing memory areas allowed.

If you want to automatic verfification of vector sizes, and so on, you will only find this in something else level languages - Java, Go, Pythn, Ruby, etc... In C, and C++ is you and the CPU.

  • Thank you so much, you’re great!

3

By reducing the reserved space to exemplo for 3 bytes, the content of these 3 bytes is 'T', 'e', 's' (notes especially the absence of '\0'), that is, this content no longer gives a string.
As you pass that nonstring for printf() anything can happen: it is Behavior Not Defined.

An example of this behavior is the program doing what you expect ... except on New Moon Fridays.

Try

exemplo = realloc(exemplo, 3);
exemplo[2] = 0; // fazer uma string
printf("%s\n", exemplo);

or

exemplo = realloc(exemplo, 3);
printf("%.3s\n", exemplo); // imprimir 3 caracteres excepto se houver um '\0' antes

Browser other questions tagged

You are not signed in. Login or sign up in order to post.