-2

I am trying to convert a string that has been passed to this function from lowercase to uppercase. I keep getting a seg fault, and cannot determine why.

void uppercase(char* input)
{
    int str_size = strlen(input);
    char *string = input;
    for (int i = 0; i < str_size; i++)
    {
      string[i] += -32;
      printf("%c", string[i]);
    }
    return;
}

Function calling the function uppercase:

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

int main(void)
{

  uppercase("max");

  return(0);

}

3 Answers3

1

The string that you are passing is a literal possibly present in read-only memory (since it is a string literal which is a constant) which you aren't allowed to modify. Hence the error.

Store the string in a character array and then pass that to the function.

char str[]="max";
uppercase(max);

http://www.geeksforgeeks.org/storage-for-strings-in-c/

https://softwareengineering.stackexchange.com/questions/294748/why-are-c-string-literals-read-only

J...S
  • 5,079
  • 1
  • 20
  • 35
0

As @dasblinkenlight said, you cannot modify a string literal.

Try this instead:

int main(void)
{
  char str[4] = "max";
  uppercase(str);

  return(0);
}

Or you can also malloc a string and pass it in.

TheGreatContini
  • 6,429
  • 2
  • 27
  • 37
0

You cannot pass string literals as an argument to the function. try storing it first in array and then pass it to the function.

  #include <stdio.h>
  #include <string.h>
  void uppercase(char* input)
  {
  int str_size = strlen(input);
  char *string = input;
  for (int i = 0; i < str_size; i++)
  {
  string[i] += -32;
  printf("%c", string[i]);
  }
  return;
  }

  int main(void)
  {
  char str[]="max";
  uppercase(str);
  return(0);
  }
Vivek Singh
  • 114
  • 1
  • 8