0

`i'm trying to reverse each word in a sentence with the positions of the words fixed. the line while(c!=' ') segfaults each time.Can somebody please let me know where i'm going wrong?here goes my code.

#include<stdio.h>

void swap(char *i, char *j)
{
    char t;
    t = *i;
    *i = *j;
    *j = t;
}

void reverse(char *s, char *e)
{
    char *i, *j;
    i = s;
    j = e;

    while(i <= j)
    {
        swap(i, j);
        i++;
        j--;
    }
}

int main()
{
    int check = 0;
    char *a= (char*) malloc(100*sizeof(char));
    char *c, *b, *t;
    char *s = ' ';
    printf("enter your sentence\n");
    fgets (a, 100, stdin);
    if ((strlen(a) > 0) && (a[strlen(a)-1] == '\n'))
        a[strlen(a)-1] = '\0'; 

    printf("\nyour stat: %s  and size is %d\n", a, strlen(a));

    b = a;
    c = a;

    while(*b != ' ')
        b++;

    b--;

    while(!check)
    {
        reverse(c, b);
        t = c;
        c = b;
        b = t;
        while(*c != ' ')// segmentation fault :|
            c++;
        while(*c == ' ')
            c++;

        b++;

        while(*b == ' ')
            b++;

        while((*b != ' ') && (*b != '\0'))
        {
            if(*b = '\0')
            {
                check = 1;
                b--; 
                reverse(c, b);
                break;
            } 
            b++;
        }

        b--;
    } 

    printf("\n reversed stat is : %s\n",a);
    return 0;
}
isedev
  • 18,848
  • 3
  • 60
  • 59
  • Please indent your code, plus random quotes in line 7. Wish i had 125 points –  Oct 03 '14 at 07:15
  • smells like homework to me – Lukáš Rutar Oct 03 '14 at 07:16
  • Format your code properly if you want someone to answer. – Jabberwocky Oct 03 '14 at 07:17
  • Why not step through the code in your debugger to see what's going wrong? That will be a much quicker solution than asking others to debug this for you, and you'll learn a lot more in the process. – Paul R Oct 03 '14 at 07:24
  • 2
    Use better variable names than single letters. And [please don't cast the return value of `malloc()` in C](http://stackoverflow.com/a/605858/28169). – unwind Oct 03 '14 at 07:31
  • `char *s = ' ';` should give you a compiler warning (conversion from integer to pointer without a cast). Please turn on compiler warnings and fix the issues the compiler complains about! – Klas Lindbäck Oct 03 '14 at 07:32

5 Answers5

1

You can improve your code in a few places to make it more robust. The real problem is that you are using

if(*b = '\0') // This assigns the null character to *b

instead of

if(*b == '\0') // This compare whether *b is the null character

Update

Things you can do to improve your code:

  1. You can use an array and not have to use malloc.

    Instead of

    char *a= (char*) malloc(100*sizeof(char));
    

use

    char a[100];
  1. Write couple of helper functions to help skip white space and skip non-white space.

    char* skipWhiteSpace(char* in)
    {
       while (isspace(*in) && *in != '\0') ++in;
       return in;
    }
    
    char* getEndOfNonWhiteSpace(char* in)
    {
       while (!isspace(*in) && *in != '\0') ++in;
       return in-1;
    }
    

    Then, the core of main can be simplified. main can be:

    int main()
    {
       char a[100];
       char *c, *b;
       printf("enter your sentence\n");
       fgets (a, 100, stdin);
       if ((strlen(a) > 0) && (a[strlen(a)-1] == '\n'))
          a[strlen(a)-1] = '\0'; 
    
       printf("\nyour stat: %s  and size is %zu\n", a, strlen(a));
    
       c = a;
       while(1)
       {
          c = skipWhiteSpace(c);
          b = getEndOfNonWhiteSpace(c);
    
          reverse(c, b);
    
          c = b+1;
          if (*c == '\0' )
          {
             break;
          }
       } 
    
       printf("\n reversed stat is : %s\n",a);
       return 0;
    }
    
R Sahu
  • 204,454
  • 14
  • 159
  • 270
1

The failing line will happily continue past the end of the string.

You need to also check for end of string:

    while(*c && *c != ' ') 
Klas Lindbäck
  • 33,105
  • 5
  • 57
  • 82
0

change if(*b = '\0') with if(*b == '\0')

here :

 while((*b != ' ') && (*b != '\0'))
  {
            if(*b = '\0')  // here is problem change it with if(*b == '\0')
            {
                check = 1;
                b--; 
                reverse(c, b);
                break;
            } 
            b++;
  }
Rustam
  • 6,485
  • 1
  • 25
  • 25
0
if(*b = '\0')

This condition of yours is assigning '\0' to *b, not checking in *b is equal to '\0 or not. change it to

if(*b == '\0')
Haris
  • 12,120
  • 6
  • 43
  • 70
0

A couple pieces of advise

  • allocated memory must be free-d
  • include header files for system calls (malloc, strlen, etc)
  • in comparisons, use the form CONSTANT compared to "variable value"
  • instead of hopping and skipping single characters, use appropriate system calls: strrchr and strcat

This version also solves the problem of the line break on different platforms.

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

int
main (int argc, char *argv[])
{
    char *sentence;
    char *gap;
    char *space = " ";
    char *reversed;
    size_t size;
    int len = 0;

    if (-1 == getline (&sentence, &size, stdin)) {
        return -1;
    }

    len = strlen (sentence);

    /* Is a line-feed the last character ? */
    gap = strrchr (sentence, '\n');
    if (NULL != gap) {
        sentence[--len] = '\0';
    }

    /* Is a carriage return the last character ? */
    gap = strrchr (sentence, '\r');
    if (NULL != gap) {
        sentence[--len] = '\0';
    }

    reversed = malloc (len);
    if (NULL == reversed) {
        return -2;
    }

    /* is there a right-most space character ? */
    while (NULL != (gap = strrchr (sentence, ' '))) {
        /* turn it into a string end */
        *(gap++) = '\0';
        /* append the "word" after the gap to the reversed buffer */
        strcat (reversed, gap);
        strcat (reversed, " ");
    }

    /* the last "word" must be appended, too */
    strcat (reversed, sentence);
    printf ("Reversed: %s\n", reversed);
    free (reversed);

    return 0;
}
C D
  • 56
  • 4