0

The below code is not showing any output after running, But on debugging it is showing Segmentation fault inside 3rd if statement 1st line string[index] = string[i]; please help why it is happening,

Please explain in simple words, Thanks a lot.

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

void parse(char *string);

int main() {
    char *html = "<h1> This is html heading </h1>";
    parse(html);
    printf("%s", html);

    return 0;
}

void parse(char *string) {
    int index = 0;
    int inside;
    
    for (int i = 0; i < strlen(string); i++) {
        if (string[i] == '<') {
            inside = 1;
            continue;
        }
        else if (string[i] == '>') {
            inside = 0;
            continue;
        }
        if (inside == 0) {
            string[index] = string[i];
            index++;
        }
    }
    string[index] = '\0';
}

Expected output

" This is html heading "
user438383
  • 5,716
  • 8
  • 28
  • 43
  • 4
    In `main`, `html` points to a string constant. You can't modify a string constant. Change `html` to an array instead. – Tom Karzes Apr 30 '22 at 07:40
  • 1
    ^^^^ In `main`, `char *html = ...` ==> `char html[] = ...` – WhozCraig Apr 30 '22 at 08:10
  • Does this answer your question? [What is the difference between char array and char pointer in C?](https://stackoverflow.com/questions/10186765/what-is-the-difference-between-char-array-and-char-pointer-in-c) – kaylum Apr 30 '22 at 08:11

1 Answers1

0

Your code creates a core dump at 5th iteration of for (i = 4) because it's the moment where your code assign a value of a string to its self (line 28, you can't do this!). Also you shouldn't assign the null character '\0', line 3, because it does it automatically the compiler.

So, you can create another char (support array) in size of strlen(html) and fill it with correct characters.

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

void parse(char *string, char suppArr[]);

int main() {
    char *html = "<h1> This is html heading </h1>";
    
    // declare a support array
    char suppArr[strlen(html)];

    parse(html, suppArr);

    // print the support array
    printf("%s\n", suppArr);

    return 0;
}

void parse(char *string, char suppArr[]) {
    int index = 0;
    int inside;
    
    for (int i = 0; i < strlen(string); i++)
    {
        if (string[i] == '<')
        {
            inside = 1;
            continue;
        }
        else
            if (string[i] == '>')
            {
                inside = 0;
                continue;
            }
        
        if (inside == 0)
        {
            // fill support array
            suppArr[index] = string[i];
            index++;
        }
    }
}

Note: You could optimize this code with malloc(), realloc() and free() functions.