-1

I have written a program in C to lower a string when compile it in gcc, it crashes when run. But in MSVC program run smoothly.

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

char *strlower(char *s){
    for ( ; *s; ++s) *s = tolower(*s);
    return (char *)s;
}

int main(){
    char *c = "HELLO";

    strlower(c);
    printf("%s",c);
    return 0;
}

if variable c is array then program works in both compiler. Why not work when using pointer in gcc ?

Ekramul Hoque
  • 4,957
  • 3
  • 30
  • 31
  • 2
    Modifying a string literal gives undefined behaviour. When behaviour is undefined, anything is allowed to happen, including different behaviours from different compilers. Both compilers are correct. – Peter Nov 17 '16 at 09:45

1 Answers1

2

In C all string literals are read only arrays of characters. Trying to modify a string literal leads to undefined behavior. That's the reason you should only use const char * when having pointers to string literals.

Try to use your own array instead:

char c[] = "HELLO";
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621