ERJAN
ERJAN

Reputation: 24500

why this lowercase function in C give me segfault memory error?

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


char* my_downcase(char* param_1) {
   int c = 0;

   while (param_1[c] != '\0') {
      if (param_1[c] >= 'A' && param_1[c] <= 'Z') {
         param_1[c] = param_1[c] + 32;
      }
      c++;
   }
   printf("%s", param_1);
   return param_1;
}

int main(){
    char *r = "ABC";
    char *res = my_downcase(r);

    return 0;
}

I'm lower casing using asci table. But when i compile and run it , it gives me segfault error, why?

Upvotes: 1

Views: 86

Answers (1)

Nate Eldredge
Nate Eldredge

Reputation: 58493

Your pointer r is pointing to a string literal, and string literals are not allowed to be modified.

Try instead

char r[] = "ABC";

which will make r an ordinary array which you can modify, initialized with the string "ABC".

Upvotes: 1

Related Questions