Farhad Farhad - 20 days ago 6
C Question

Same program GCC crashes but msvc works

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 ?

Answer

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";