Malloc and string length | Sololearn: Learn to code for FREE!
¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita
+ 1

Malloc and string length

Why does the length of the input changes when i use memory allocation ? It gives the same output but not the same length https://code.sololearn.com/c0VBrO0TastU/?ref=app https://code.sololearn.com/cTvVU5ssk2HH/?ref=app

10th Feb 2023, 12:32 AM
Shimaa
Shimaa - avatar
2 Respuestas
+ 5
Dark there is a problem with trying to use memory after freeing it. Once memory is freed, it is available to be allocated and overwritten by any other process. In fact, that is what is happening. The call to printf evidently overwrites the memory formerly allocated to sen. Move the printf to occur before the free statements. It is common practice to set the pointer equal to null after freeing it in order to prevent accidental references to freed memory later in the program.
10th Feb 2023, 3:18 AM
Brian
Brian - avatar
+ 1
Brian Oh i got it, tried it and worked 😅 . thanks for explaining ^^
10th Feb 2023, 2:44 PM
Shimaa
Shimaa - avatar