I'm trying to figure out the issue with this code:
int main(int argc, char *argv[])
{
char *s;
scanf("%s\n", s);
char *t = malloc(sizeof(*s) 1);
strcpy(t, s);
t[0] = toupper(t[0]);
printf("s: %s\n", s);
printf("t: %s\n", t);
free(t);
return 0;
}
I was trying to upper case the first alphabet of my input to get for example hi!
changed into Hi!
.
CodePudding user response:
You are using scanf on a char* without first allocating memory to it. This may lead to segmentation fault. In fact, the following code :
#include<stdio.h> int main() { char* str; scanf("%s", str); printf("%s\n", str); return 0; }
does give segmentation fault sometimes. Instead you can use a
char
array instead of achar*
if you want to avoidmalloc
beforescanf
. You can usefgets
instead ofscanf
to prevent writing out of bounds or you can check withscanf
itself like this:char s[100]; if(scanf("