OiO.lk Blog C++ Segmentation fault due to SIGBUS
C++

Segmentation fault due to SIGBUS


I have written a code, to reverse the words in a string, and it works for some test cases. But the problem is for remaining cases, it returns segmentation fault. When I’m checking for errors, I found that the error is due to SIGBUS, bus error, not SIGSEGV. I’ve never encountered bus error sofar, and I couldn’t understand the nature of problem. So, I request to find the error, or maybe correct my problem.

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

void reverse(char *);

int main()
{
    char str[100];
    scanf("%[^\n]",str);

    reverse(str);
    int len = strlen(str),i = 0,cn = 0;
    while(i <= len)
    {
        if(str[i] != ' ' && str[i] != '\0')
            cn++;
        else
        {
            int j = i - cn,k = i - 1;
            while(j != k)
            {
                char tm = str[j];
                str[j++] = str[k];
                str[k--] = tm;
            }
            cn = 0;
        }
        i++;
    }
    printf("%s\n",str);
}

void reverse(char *str)
{
    int i = 0,len = strlen(str);
    while(i < len/2)
    {
        char tm = str[i];
        str[i] = str[len-1-i];
        str[len-1-i] = tm;
        i++;
    }
}



You need to sign in to view this answers

Exit mobile version