'No output after running C code. Segmentation fault on debugging
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 "
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | AndreVale69 |
