Simple line execution error in C?
You have allocated space for one pointer, s1
but not the bytes it points to s1
.
The solution is to dynamically allocate memory for s1
:
s1 = (char *)malloc(strlen(s2) + 1);
strcpy(s1, s2);
Be aware that you need to allocate one more byte of memory (+1 in the call malloc
) than the number of characters in s2
, because there is an implicit byte at the end NULL
.
See Memory Management (Stack Overflow) for details .
source to share
What everyone says, you need to allocate space for s1. What everyone else has posted will work very well, however, if you want an easier way to allocate space for an existing string and copy it into a new pointer, then use strdup like this:
#include <stdio.h>
#include <string.h>
#include <math.h>
using namespace std;
int main() {
const char s2[] = "asdfasdf";
char* s1;
s1 = strdup(s2);
printf("%s", s1);
return 0;
}
Someone mentioned strdup before, this would be the way to use it. Most systems should support it as it is in the standard C libraries. But, apparently, some do not. So if it returns an error, write your own using the already mentioned method, or just use the already mentioned method;)
source to share
No one has yet pointed out the potential of strdup (String Duplicate) to solve this problem.
#include <stdio.h>
#include <string.h>
#include <math.h>
using namespace std;
int main() {
const char s2[] = "asdfasdf";
char* s1;
s1 = strdup(s2); // Allocates memory, must be freed later.
printf("%s", s1);
free(s1); // Allocated in strdup, 2 lines above
return 0;
}
source to share
You have to allocate memory to s1 pointer. If you don't, it will point to somewhere unknown and thus reach a segmentation fault. The correct code should be:
#include <stdio.h>
#include <string.h>
#include <math.h>
int main() {
const char s2[] = "asdfasdf";
char* s1 = malloc(21 * sizeof(s2[0]));
strcpy(s1,s2);
printf("%s",s1);
return 0;
}
source to share