-4

i have a segmentation fault error when i want to run the executable file

void lowerupper(char *s){
    int i ;

    int a = strlen (s);

    printf("%d\n", a);

    //fails here segmentation fault

    for (i=0 ; i < a-1 ; i++){

        if( (s[i] >= 97) && (s[i] <= 122)){
             s[i] = s[i] - 32;
        }
    }
}

int main(void) {

   char* string1 = 'HeLlo wOrlD';

   printf("%s\n", string1);

   lowerupper(string1);

   printf("%s\n", string1);

   return 0;
}
M Oehm
  • 28,726
  • 3
  • 31
  • 42

2 Answers2

1

You can not modify string1. In fact when you declare a string like this

 char* string1 = "HeLlo wOrlD";

The string could be stored into a READ-ONLY memory area, it means that you can read it, but not modify it. If you do

char array[] = "hello world";

Then it creates a read-only string, and copies the characters into array, you'll be able to modify it (into array). You are invited to declare read-only strings with the keyword const.

 const char *string1 = "HeLlo wOrlD";
Weather Vane
  • 33,872
  • 7
  • 36
  • 56
Gam
  • 684
  • 1
  • 8
  • 17
-1

You might have been passing address of local variable to the function. You should allocate memory in heap and then pass that variable to function. This code works here:

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

void lowerupper(char *s)
{
    int i ;
    int a = strlen (s);
    printf("%d\n", a);

    for (i=0 ; i < a-1 ; i++)
    {
        if( (s[i] >= 97) && (s[i] <= 122))
        {
             s[i] = s[i] - 32;
        }
    }
}

int main(void) 
{
    char *ss=malloc(10);
    strcpy(ss,"hello\n");
    lowerupper(ss);
    printf("%s",ss);
    return 0;
}

Sample Output:

6

HELLO

0___________
  • 60,014
  • 4
  • 34
  • 74
krpra
  • 466
  • 1
  • 4
  • 19