This code compiles fine but give segmentation fault error while running? Can anyone tell why?
#include <stdio.h>
#include <string.h>
#include <math.h>
int main() {
const char s2[] = "asdfasdf";
char* s1;
strcpy(s1, s2);
printf("%s", s1);
return 0;
}
You allocated space for a single pointer,
s1, but not the bytes pointed at bys1.A solution is to dynamically allocate memory for
s1:Keep in mind that you need to allocate one more byte of memory (the +1 in the call to
malloc) than the number of characters ins2because there is an implicitNULLbyte at the end.See C Memory Management (Stack Overflow) for more information.