skydereign wrote:That's because the char* isn't pointing to any memory. You would either need to allocate some memory for the char* or just use a char array.
Not quite like so, skydereign.
It crashes exactly, because it DOES point to a memory, to an arbitrary memory address (obviously as the pointer points to a garbage value, since not initialized). Sometimes OS would not allow it, sometimes the memory address will not be accessible/immutable, sometimes it will not actually crash! This is a complete
Undefined Behavior.
To make it safe, without causing it to crash, initialize it to 0.
- Code: Select all
typedef struct { char* ptr; } mystruct;
- Code: Select all
mystruct obj = { NULL };
In that case, this is the so called NULL Pointer and this is what actually literally doesn't point to anywhere. In that case It is very unlikely that will crash, especially on using
strcpy, because such functions are designed to either return error or EOF if the pointer given on their argument is NULL and they will be unable to perform the task, therefore, nothing will be printed, copied or modified and the function will simply - fail