Question

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;
}
Was it helpful?

Solution

You allocated space for a single pointer, s1, but not the bytes pointed at by s1.

A solution is to dynamically allocate memory for s1:

s1 = (char *)malloc(strlen(s2) + 1);
strcpy(s1, s2);

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 in s2 because there is an implicit NULL byte at the end.

See C Memory Management (Stack Overflow) for more information.

OTHER TIPS

You didn't allocate memory for s1. You have a pointer to s1 but no memory allocated for the strcpy to copy the value of s2 into.

char *s1 = malloc( strlen(s2) + 1 );

strcpy( s1, s2 );

You have not allocated any memory to s1. It is a pointer to nothing.

char* s1 = malloc(sizeof(s2));
strcpy(s1, s2);
printf("%s", s1);
free(s1);

The problem is that s1 does not have any memory associated with it. strcpy does not call malloc().

You could either do:

char s1[10];

or

char *s1 = malloc(10);

What they all said, you need to allocate the space for s1. What everyone else has posted will work just fine, however, if you want a simpler 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 earlier, that would be a way to use it. Most systems should support it since it is in the standard C libaries. But apparently some don't. So if it returns an error either write your own using the method already mentioned, or just use the method already mentioned ;)

No one yet has pointed out the potential of strdup (String Duplicate) to address 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;
}

You need to allocate the destination (and using namespace std; isn't C but C++, the rest of the code is C).

You have to allocate memory to the pointer s1. If you don't do that, it will be pointing somewhere unknown, and thus arriving at the 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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top