I understand that following code returns segmentation fault because it tries to write to the part of memory where q
points to (some random address) and this part of memory is not allowed to write by given process:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char* p = "Hello";
char* q;
strcpy(q, p);
printf("%s\n", q);
}
I also understand that it can be easily fixed by dynamically allocating appropriate amount of memory and pointing q
to this memory, so p
content can be safely copied to q
:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char* p = "Hello";
char* q = (char*)malloc(6*sizeof(char));
strcpy(q, p);
printf("%s\n", q);
}
But why following example is working?
#include <stdio.h>
int main(){
char* p = "Hello";
printf("%s\n", p);
}
Isn't char* p = "Hello";
also pointing to some unknown memory which is not allowed to write by given process?