0

I am trying to write a code in C, to reverse a string. Needless to say that using library functions is not an option as I am trying to build a little bit of logic. I am getting a read access violation at line 22. I tried doing this using character arrays as well as string pointer, but both give the same "access violation" result. Can somebody clear the concepts regarding the string access rules using this example?

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

int main()
{
    char reversed_string[21], input[21];// *temp;
    printf("Please enter the string(max 20 characters) : ");
    gets_s(input, 20);
    unsigned short int i, j,length;

    i = j=length = 0;
    while (input[i] != '\0')
    {
        length++;
        i = i + 1;
    }
    i = length - 1;

    while (i >= 0)
    {
        reversed_string[j] = input[i];
        i = i - 1;
        j = j + 1;
    }
    reversed_string[j] = '\0';
    
    printf("\n The reversed string is : %s.\n\n", reversed_string);
    
    system("pause");
    return 0;
}
Amit Dev
  • 59
  • 8
  • 5
    You have `while (i >= 0)` but `i` is never less than `0` because it is unsigned. It's an infinite loop. – Weather Vane Oct 13 '20 at 13:05
  • 1
    `gets_s()`, `printf()`, and `system()` are library functions! Just saying... – pmg Oct 13 '20 at 13:07
  • "It's an infinite loop" and hence a buffer overrun / access violation. Pay closer attention to types and indices! – underscore_d Oct 13 '20 at 13:08
  • "using library functions related to strings", obviously. – Amit Dev Oct 13 '20 at 13:09
  • 1
    Some help with (future) debugging ... if you know that the failure is in the `reversed_string[j] = input[i]` line of code, then verify your assumptions by printing out the indices beforehand, for example `printf("i=%d, j=%d\n", i, j)`. You'll see that just prior to the crash, the value of `i` is 65535, which obviously is wrong. How did it get that high? Work backwards. It should be -1 but it's 65535 because subtracting 1 from 0 doesn't yield a negative number when your variable is unsigned. – jarmod Oct 13 '20 at 13:26
  • 1
    How to reverse a string is a typical example of a problem that have been solved many times before, So I closed this as a duplicate. – klutt Oct 13 '20 at 13:28
  • 1
    @Weather Vane, and other who pointed this out, Yeah I missed that nuance. Thank you very much for the assistance, as I was just about to go crazy over this. – Amit Dev Oct 13 '20 at 13:42

0 Answers0