0

The following code results in a seg fault, when running in GDB it appears when the memory is changed to decrease the character by 32.

#include <stdio.h>

char *upper(char *);

int main(void) {

    char *my_word = "hello";

    printf("Upper: %s\n", upper(my_word));

    return 0;
}

char *upper(char *string) {
    while(*string != '\0') {
       *string -= 32;
        string++;
    }

    return string;
}
James Parker
  • 285
  • 3
  • 6
  • 17

1 Answers1

1

When you use string++ at the end it will point to \0.

char *upper(char *string) {
    while(*string != '\0') {
       *string -= 32;
        string++; // don't use this method here
    }
    return string; // it will return the address of \0
}

while returning it will return the address of \0. so it wont print anything.

Try the following changes-

#include <stdio.h>
#include<string.h>
char *upper(char *);

int main(void) {

        char my_word[] = "hello";

        printf("Upper: %s\n", upper(my_word));

        return 0;
}

char *upper(char *string) {
        int i;
        for(i=0;string[i];i++)
                string[i] -=32;
        return string;
}
Sathish
  • 3,740
  • 1
  • 17
  • 28