Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a string returned from my function print as garbage?

Tags:

c

string

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;
}
like image 919
user1204057 Avatar asked Mar 10 '26 03:03

user1204057


2 Answers

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:

char newstr = malloc(len);

This will need to be free()d appropriately when it is no longer used, of course.

like image 184
Perry Avatar answered Mar 12 '26 18:03

Perry


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

char *covertToUpper(char *str){
    char *newstr, *p;
    p = newstr = strdup(str);
    while(*p++=toupper(*p));

    return newstr;
}

int main (void){
    char *str = "test.pdf";
    char *upstr;

    printf("%s\n", str);
    upstr=covertToUpper(str);
    printf("%s\n", upstr);
    free(upstr);
    return 0;
}
like image 34
BLUEPIXY Avatar answered Mar 12 '26 17:03

BLUEPIXY