I am new to C and 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?

9 Answers
9

The reason you are getting junk is because you're allocating "newstr" on the stack and then returning its value. This is a big no-no in C. Every function you call afterwards, including the printf 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 or calloc and set newstr to point to it. For example, you could declare:

genrally mallocing in a conversion is not the best, it ties the conversion function to having to malloc, when there is no need for it
–
Keith NicholasFeb 25 '12 at 4:20

The original poster did not explain what API he needed. Perhaps he needed not to alter the original string for whatever reason. In any case, the principle being illustrated here in the answers is that returning a pointer to a stack allocated piece of memory causes trouble, and that's an important principle to know regardless of what the original intent was.
–
PerryFeb 25 '12 at 4:23

you are returning the newstr, but its declared on the stack, so when the function ends, its undefined what will happen. You need to either pass a pointer in to your new str, or malloc one, or just convert the pointer passed in place.

In this case, the most useful thing is to pass in a pointer for the newstre, and a length of the newstr ( saying how much space you are allowed to use in the newstr). This way you aren't tied to a malloc when converting to upper case, you can pass the same pointer for both src and dest and it will do it in place)

If you want then a function that DOES malloc, write a second function ( with a name hinting its allocating memory) which allocs the memory and uses the one that takes the pointers

Because usually you want the very same string to be converted to uppercase instead of making a new copy to use more memory. If you really want a new copy, you can always do so before calling the function that converts to uppercase. No need to mix both tasks and make them more complicated.