Why doing something like this okay
but this crashes my programCode:char *s; s = (char *)malloc(100); s[0] = 0;
What's the difference?Code:char *s.; s[0] = '0';
Why doing something like this okay
but this crashes my programCode:char *s; s = (char *)malloc(100); s[0] = 0;
What's the difference?Code:char *s.; s[0] = '0';
The difference is that in the latter, you created a pointer s, but it doesn't point to anything, so you cannot dereference it with s[0]. In the former you caused it to point to memory starting from the address returned by malloc, so s[0] is fine (but you should check that malloc did not return a null pointer).
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
Here I'm assigning s to "Hello"
But this crashes program tooCode:char *s = "Hello"; s[0] = '0';
What you should really have is
const char *s = "hello";
String constants are placed in read-only memory, so you get an exception if you try to change them.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
So when I assign memory using malloc(). they are placed in read and write memory, right??
Yes.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)