Thread: Why does this ouput random characters

  1. #1
    Registered User
    Join Date
    Sep 2006
    Posts
    5

    Why does this ouput random characters

    Code:
    #include <stdlib.h>	// for itoa() call
    #include <stdio.h>	// for printf() call
    
    char *convert(int value);
    
    int main() 
    {
    
     //print our string
     printf("%s\n", convert(123));
     getchar();
     return 0;
    }
    
    char *convert(int value)
    {
    	 char buf[5];
    	 return itoa(value, buf, 2);
    }
    Last edited by Ken Fitlike; 09-30-2006 at 04:57 PM. Reason: added code tags

  2. #2
    erstwhile
    Join Date
    Jan 2002
    Posts
    2,227
    You're trying to return a pointer from your convert function with scope local to that function. Make buf static and return that rather than the result from itoa.
    CProgramming FAQ
    Caution: this person may be a carrier of the misinformation virus.

  3. #3
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,613
    > Why does this ouput random characters ?
    Because you are returning a pointer to memory local to convert(), which when the function returns, will point to garbage. Always make sure that memory you want to use stays in scope as long as you need it, as it does in this program.
    Code:
    #include <limits.h>
    #include <stdio.h>
    
    /* Convert a number to string representation. Returns nonzero on failure; if the string was too
        short, it returns the minimum space needed. */
    int itostr (int value, char buff[], size_t size);
    
    int main(void)
    {
        int value = 123;
        char buff[5];
        if ( itostr(value, buff, sizeof buff) == 0 )
            printf("Value %d as a string: \"%s\"\n", value, buff);
        getchar();
        return 0;
    }
    
    int itostr (int value, char buff[], size_t size)
    {
        int result = 0;
        result = snprintf(buff, size, "%d", value);
        if (result >= size)
           return result;
        else
           return !result;
    }
    $ ./a
    Value 123 as a string: "123"
    Last edited by whiteflags; 10-01-2006 at 02:16 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. HELP!!!!emergency Problem~expert please help
    By unknowppl in forum C++ Programming
    Replies: 9
    Last Post: 08-21-2008, 06:41 PM
  2. HELP!!!!emergency ~expert please help
    By unknowppl in forum C Programming
    Replies: 1
    Last Post: 08-19-2008, 07:35 AM
  3. Question for Random class
    By joenching in forum C++ Programming
    Replies: 2
    Last Post: 03-20-2005, 11:22 PM
  4. non repeating random number generation?
    By gencor45 in forum C# Programming
    Replies: 1
    Last Post: 02-08-2005, 05:23 PM
  5. Another brain block... Random Numbers
    By DanFraser in forum C# Programming
    Replies: 2
    Last Post: 01-23-2005, 05:51 PM