Home > Net >  why does the code occur segmentation fault? sometimes it not occur
why does the code occur segmentation fault? sometimes it not occur

Time:02-27

I want to replace the space with " " in the sentence. for example:

Input:"How are you?"
Output:"How are you?"

and i am successfully make it in short sentence,but when i use 20 space. for example:

Input:"                    "
Output: segementation falut

I hope to find the reason,thank you everyone. This is my code in C:

char* replaceSpace(char* s ) {
    // write code here
    int len = strlen(s);//to mark the length of s
    for(int i = 0; i < len; i  )
    {
        
        if(s[i] == 32)
        {
            len = len   2;
            for(int j = 0; j < len-i-1; j  ){
                s[len-j] = s[len-j-2]; 
            }
            s[i] = '%';
            s[i 1] = '2';
            s[i 2] = '0';
        }
    }
    return s;
}

thank you so much.

CodePudding user response:

You cannot dynamically increase the length like that. You are accessing an un-allocated index outside of s, while referencing it,hence resulting in the seg fault.

CodePudding user response:

Segmentation Fault usually occurs when you try to access the unallocated portion of the memory.

The possible workaround for this problem is that you make a new string and copy all the characters (except space) normally. For each space character you encounter, you replace that with " ". So the length of the new string would be thrice as many spaces as it contains plus the rest of the characters (if any).

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


// Construct an ADT called String
typedef struct {
  char *str;
  size_t length;
  size_t str_size;
} String;


// Initialize our ADT
String *initStr(void);
// Free the memory allocated for `String`
void destroyStr(String *);
// Get input from `stdin`
String *input(char *);
// Count the total number of given
// character in the string
size_t count(String *, char);
// Replace each spaces in the string
// with its hex value
String *convert(String *);


int main(void)
{
    String *s = input("Input: ");
    s = convert(s);
    printf("Output: %s\n", s->str);
    
    destroyStr(s);
    return 0;
}


String *initStr(void)
{
  String *s = malloc(sizeof(String));
  s->str = malloc(sizeof(char));
  s->str[0] = '\0';
  s->length = 0;
  s->str_size = 1;
  return s;
}


String *input(char *label)
{
  printf("%s", label);
  String *s = initStr();
  
  int c;
  while ((c = getc(stdin)) != '\n' && c != EOF) {
    // Dynamically allocate string. If the string
    // length is equal to the internal size, allocate
    // twice as of current length.
    if (s->length   1 == s->str_size) {
      size_t ssize = s->str_size;
      s->str = realloc(
        s->str, 2 * ssize * sizeof(char)
      );
      
      if (s->str == NULL)
        return NULL;
      
      s->str_size = 2 * ssize;
    }
    s->str[s->length  ] = c;
  }
  
  s->str[s->length] = '\0';
  return s;
}


void destroyStr(String *s)
{
  free(s->str);
  free(s);
}


size_t count(String *s, char c)
{
  size_t count = 0;
  for (size_t i = 0; i < s->length;   i)
    if (s->str[i] == c)
        count;
  return count;
}


String *convert(String *old_s)
{
  size_t total_spaces = count(old_s, ' ');
  
  // Return the original string if there are
  // no spaces in it
  if (total_spaces == 0)
    return old_s;
  
  // The new string will contain thrice as many characters
  // for each space plus the other characters
  size_t new_s_len = (
    3 * total_spaces   
    old_s->length - total_spaces
  );
  
  String *new_s = initStr();
  new_s->str = malloc( (new_s_len   1) * sizeof(char) );
  new_s->str_size = new_s_len   1;
  
  for (size_t i = 0; i < old_s->length;   i) {
    if (old_s->str[i] == ' ') {
      new_s->str[new_s->length  ] = '%';
      new_s->str[new_s->length  ] = '2';
      new_s->str[new_s->length  ] = '0';
    }
    else
      new_s->str[new_s->length  ] = old_s->str[i];
  }
  
  new_s->str[new_s->length] = '\0';
  destroyStr(old_s);
  return new_s;
}

Since C does not have any built-in String datatype, we tried to somewhat emulate the datatype using struct and character array. We would also have to handle the memory managements ourselves. This might get cumbersome and is generally not so closely related with the actual problem. Therefore I would urge you to move either to C or Rust.

  • Related