Thread: 135073

  1. #1
    Registered User
    Join Date
    Jun 2008
    Posts
    127

    135073

    Whenever I run this program(on Linux):
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    int *letter_count(char *s);
    int main(int argc,char **argv)
    {
    	int *lc=calloc(26,sizeof(char));
    	lc=letter_count(argv[1]);
    	for(int i=0;i<26;i++)
    	{
    		printf("%c: %d\n",(char)(i+'a'),lc[i]);
    	}
    	return 0;
    }
    int *letter_count(char *s)
    {
    	int *lc=calloc(26,sizeof(char));
    	for(int i=0;s[i];i++)
    	{
    		lc[(int)(s[i]-'a')]++;
    	}
    	return lc;
    }
    I keep getting 135073 for 'k' when no k's has been entered. I tracked it back to the calloc which seems to be where k gets its strange value. Why would calloc produce this number?

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    So lc is 26 bytes long. That means you have room to store counts for a, b, c, d, e, and f. Apparently you get lucky with g, h, i, and j, since they should be really really big too. Maybe you should allocate enough space for 26 ints instead?

  3. #3
    Registered User
    Join Date
    Jun 2008
    Posts
    127
    I meant to use int. Thanks for the catch!

  4. #4
    Registered User
    Join Date
    Dec 2006
    Location
    Canada
    Posts
    3,229
    haha and nice thread subject you have there.

  5. #5
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    You fail to free your allocated memory.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  6. #6
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by Elysia View Post
    You fail to free your allocated memory.
    And you are allocating twice: Once in main, and once in the letter_count function, which is then overwriting the value allocated in main, so you "loose" the original pointer of the memory allocated in main - you should either allocate in main and pass the pointer to the letter_count function, or allocate in the letter_count function only.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed