0

The point of the code void rotate_in_place(char *str, unsigned int disp) is to take in a string and integer and rotate each character of the string by the disp integer.

When running my code I keep getting a Segmentation fault.

Coding Language: C

I have implemented my code as follows:

void rotate_in_place(char *str, unsigned int disp)
{
  int i=0;
  if(disp<0 || disp>2600)
    printf("Illegal Input");
  else
    disp= disp%26;
  for(i =0; i<strlen(str); i++){
    if(str[i]>='a' && str[i]<='z'){
      str[i]= str[i]+disp;
      if(str[i]>'z')
    str[i]=str[i]-'z'+'a'-1;
    }
    else if(str[i]>='A' && str[i]<='Z'){
      str[i]= str[i]+disp;
      if(str[i]>'Z')
        str[i]=str[i]-'Z'+'A'-1;
    }
    else
      str[i]=str[i];
  }
  str[i]='\0';
  printf("%s", str);
}

int main(){

rotate_in_place("Hello World", 5);
rotate_in_place("Hi", 13);
rotate_in_place("World", 42);
return 0;

}

I am not yet done with the code, so it may be incorrect but I cannot run it without getting a Segmentation fault.

Is there any reason why I keep getting this Segmentation fault, is there a memory leak in my code?

  • 2
    The first step is to run your program in a debugger and see which expression (on which line) is producing a segfault. – John Zwinck Mar 05 '21 at 22:52
  • 2
    You are not allocating any memory dynamically, so I really doubt this piece of code causes a memory leak. – Marco Bonelli Mar 05 '21 at 22:55
  • 5
    Neither the final `else str[i]=str[i];` nor the hard-termination `str[i]='\0'` should be necessary in this code, btw. And this code isn't "running" anywhere that we can see. My crystal ball + my leet mind-reading skillz tells me you're executing it on a read-only const literal string by address in the calling code you've chosen for whatever reason *not* to include. Now how about posting a proper [mcve] that we can run to reproduce your precise issue. – WhozCraig Mar 05 '21 at 22:56
  • 2
    Memory leaks don't cause segmentation faults. Segmentation faults occur when you try to access memory that can't be accessed in the way you try. – Barmar Mar 05 '21 at 23:03
  • Note that `str[i]+disp` causes signed integer overflow (`char` is signed), which is undefined behavior, you should first check and only then increment/decrement of the appropriate amount. – Marco Bonelli Mar 05 '21 at 23:04
  • @MarcoBonelli, the standard arithmetic promotions will result in `str[i]` being converted to `unsigned int` for that addition (since that is the type of `disp`), so no, there is no signed integer overflow there. But perhaps you meant that assigning the result back to `str[i]` can exhibit signed integer overflow, which indeed it can. – John Bollinger Mar 05 '21 at 23:18
  • @JohnBollinger oh right, it's the assignment, not the operation itself. – Marco Bonelli Mar 05 '21 at 23:20

0 Answers0