Search code examples
cstringlowercase

lower case string in c


i had a few line here :

#include <stdio.h>

char *tolower(char *data)
{
    char *p = data;
    while(*p)
    {
        printf("nilai p : %c\n",*p);
            if(*p >= 'A' && *p <= 'Z')
            {
                *p += ('a' - 'A');
            }
        p++;
    }
    return p;

}

int main()
{

    char *a = "HajAR BleH";
    char *b = tolower(a);

    printf("nilai b : %s\n",b);
    printf("nilai a - A : %d\n",'a' - 'A');
return 0;
}

next, compiled, running on gdb, and segmentation traced

xxx@aaa:/tmp$ gcc -o aa aa.c --debug
xxx@aaa:/tmp$ gdb -q aa
Reading symbols from /tmp/aa...done.
(gdb) r
Starting program: /tmp/aa 
nilai p : H

Program received signal SIGSEGV, Segmentation fault.
0x0804841e in tolower (data=0x804855e "HajAR BleH") at aa.c:11
11                  *p += ('a' - 'A');
(gdb) 

question

1. i think *p += ('a' - 'A'); will equal as 'H' += ('a' - 'A') and equal with 72 += 32 but, accidentally segmentation fault, how come it could be ?

2. why need to add ('a' - 'A') to make char/byte get lower ?

thats all for now, thank in advance


Solution

  • You are trying to modify a string literal. Change:

    char *a = "HajAR BleH";
    

    to:

    char a[] = "HajAR BleH";
    

    Also, there already is a standard library function called tolower(), which you should in fact be using in your code. Call your own function something else.