I am trying to convert the string to upper case, e.g. convert test.pdf to TEST.PDF. However, when I try to print returned value using printf, it prints some junk value. What am I doing wrong?
char *covertToUpper(char *str)
{
int i = 0;
int len = 0;
len = strlen(str);
char newstr[len+1];
for(i = 0; str[i]; i++)
{
newstr[i] = toupper(str[i]);
}
//terminate string
newstr[i]= '\0';
return newstr;
}
The reason you are getting junk is because you’re allocating”
newstron the stack and then returning its value. This is a big no-no in C. Every function you call afterwards, including theprintf()function itself, will trample all over what you just allocated.C is unfortunately a bit of a dangerous language. It will not stop you from returning a string you allocated on the stack to a calling function even though that memory is no longer safe to use once the function it was declared in returns.
Instead of allocating the string this way, you need to allocate fresh memory on the heap for it using
malloc()orcalloc()and setnewstrto point to it. For example, you could declare:This will need to be
free()d appropriately when it is no longer used, of course.