How this works? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How this works?

Isn't it a fact that we have to allocate memory for a pointer before using it to store any values? I don't understand how my code(below) works. Can you explain it for me? Thank you https://code.sololearn.com/caosTcnA7era/?ref=app

15th Jun 2021, 3:52 AM
Rishi
Rishi - avatar
4 Answers
+ 3
in fact if I try to run it in the playground it gives an error. However in C, even depending on the compiler and the ecosystem in which the program acts, a pointer is just an address in memory. writing data to an uninitialized memory location with an adequate value can cause problems because C (at least classic compilers) do not waste time initializing variables or checking if the programmer is wrong to allocate/deallocate memory or to write a lean memory address in a pointer . it starts from the assumption that the programmer knows what he is doing ... or at least it was so.
15th Jun 2021, 4:42 AM
Ciro Pellegrino
Ciro Pellegrino - avatar
+ 2
Rishi The behavior of your code is undefined. In your code, 'ptr' holds an undefined value (in SL, it shows (nil) everytime I run it). The lower addresses of the RAM allocated to the process are usually reserved for storing the code and for globals, constants, etc. You're free to access any address in the stack or the heap, but you're not allowed to do so with the other partitions of the memory. Doing so will result in the program crashing, as you might overwrite any important information found at the address.
15th Jun 2021, 5:27 AM
Calvin Thomas
Calvin Thomas - avatar
+ 1
Calvin Thomas oh okay✌️
15th Jun 2021, 5:29 AM
Rishi
Rishi - avatar
0
Ciro Pellegrino oh yes it gives an error. Actually it worked in Cxxdroid so only I got this doubt. Now it's clear for me. have a nice day!
15th Jun 2021, 4:44 AM
Rishi
Rishi - avatar