Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

getting "Segmentation fault (core dumped) error and i don't know why

#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    string a = "bob";
    string b = "steve'";
    for (int c = 0, n = strlen(b); c < n; c++)
    {
        a[c] = b[c];
        if (a[c] == '\0')
        {
            a[c+1] = '\0';
            a[c] = b[c];
        }
        if (b[c] == '\0')
        {
            a[c] = '\0';
            break;
        }
    }
    printf("%s", a);
}

The error happens at the line that says a[c] = b[c] first, or the 12th line of code. The point of the code is to try and change string a to string b. However, it seems that I cant make two characters of arrays equal. Is there some way this is possible?

To make the those strings the same, I simply tried making their characters equal. It resulted in a Segmentation fault (core dumped).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

For starters it seems there is a typo

"steve'"
      ^^

Nevertheless pointers a and b declared like

string a = "bob";
string b = "steve'";

where the name string is an alias for the type char * point to string literals "bob" and "steve".

In this for loop

for (int c = 0, n = strlen(b); c < n; c++)
{
    a[c] = b[c];
    //...

you are trying to change a string literal. Any attempt to change a string literal results in undefined behavior. Moreover within the if statement

    if (a[c] == '\0')
    {
        a[c+1] = '\0';
        a[c] = b[c];
    }

you are trying even to write in memory outside the string literal.

From the C Standard (6.4.5 String literals)

7 It is unspecified whether these arrays are distinct provided their
elements have the appropriate values. If the program attempts to
modify such an array, the behavior is undefined.

Instead of pointers to string literals you need to declare at least one character array where a string literal will be copied.

For example you could write

#include <stdio.h>

int main(void)
{
    char b[] = "steve";
    char a[sizeof( b )] = "bob";

    for ( size_t i = 0; ( a[i] = b[i] ) != '\0'; );

    puts( a );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading