While running following code, my program crashes unexpectedly!
#include<stdio.h>
#include<string.h>
int main(){
char *str = NULL;
strcpy(str, "swami");
printf("%s", str);
return 0;
}
But if I do like this:
#include<stdio.h>
#include<string.h>
int main(){
char *str;
strcpy(str, "swami");
printf("%s", str);
return 0;
}
This code works fine and generates correct output!
I am using gcc compiler(codeblocks IDE). Also, both the codes lead to program crash in DevCpp. Can anyone please explain me why this is so!?
You cannot write to
NULLpointers.In the second case, it happened that your pointer was randomly initialized to a valid location in your program’s memory. That is why you could do a
strcpyinto it.Change both programs to have
or the option with
callocbefore thestrcpy. (sizeis the size of the space you want to reserve.)As per comment, you can also change the declaration of
strto bechar str[6](or more).Last edit: I’ll present you this picture showing the memory of your program and the pointers:
The gray areas and the red one are forbidden (you cannot write or read from them; the top gray one is for kernel memory while the others are spaces not yet reclaimed). The red area at the bottom is the special 0 page. Since
NULLis0yourstr = NULLwill point to this and your program will fail.If you don’t assign anything to
strit will end up pointing randomly. It can still point to the red area or to a grey area -> your program will fail. It could point to a green or blue (both hues) area, making your program work (excepting the cases where it is pointing to a read-only location and you write to it). Allocating area for the pointer makes it point to the green area, enlarging it to the top.The other option, with
str[6]enlarges the stack area to bottom. All local variables have space reserved into the stack while all space allocated withmalloc,realloc,callocand other friends goes into the heap.Lastly, have a look at a blog article about the difference between
char[]andchar *.PS: If you’d want to use a GNU extension you can look into the
asprintffunction. It would allocate space for a string and write some content there:or
But, if you want portability, you’d stay away from this function.