C Newbie: Help with Simple Function

Spoiler: I am an absolute beginner to C. I quickly threw threw together this program to test my knowledge, but my compiler is giving me errors. What is the problem and why?

#include <stdio.h>

void main()
    char *string = "abcdefghi";

    printf("%s\n\n", string);

    printf("%s\n\n", substr(string, 1, 2));

char * substr(char *string, int start, int length)
    int i;
    char *temp;

    for(i = 0; i < length; i++)
        temp[i] = string[i+start];

    return temp;


Sorry, it's like 1 AM here, I've been up trying to figure this out.

The errors are:

main.c: In function ‘main’:
main.c:9: warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘int’
main.c: At top level:
main.c:12: error: conflicting types for ‘substr’


Here are the errors I see:

Use of uninitialized pointer

In substr you declare char *temp; and then use it without initializing it to anything. This is not a compile-time error, but this program will almost certainly crash when you run it, since temp will effectively point to a random memory address. This is a case of undefined behavior, and C is chock full of it. Undefined behavior will come out of nowhere and eat your pets if you aren't careful.

Consider malloc()ing some memory, or having your function receive a pointer to a buffer where it can write the portion of the string.

Use of function not yet declared

In C you must declare functions before they are used, or at least declare their prototype. Above main()'s declaration, add this line:

char * substr(char *string, int start, int length);
No use of const where it makes sense

When assigning a string literal to a char*, that variable should be declared const. So change

char *string = "abcdefghi";


const char *string = "abcdefghi";

You will have to change your function prototype to

char * substr(const char *string, int start, int length)

which is what it should have been in the first place.

Added 2010-12-02:

substr() does not add terminating null character

The substr() function, while algorithmically correct in every other sense, does not add a terminating null character to the new string. This will cause printf() and every other string-using function (like strlen(), strcpy(), etc.) to run off the end of the string into unallocated heap memory, or stack memory (depending on how you resolve the "uninitialized pointer" issue).

To fix this, add this line immediately after the for loop, and before the return statement:

temp[i] = '\0';

Note that this should not be added in the for loop, as that would have the effect of creating a string with zero length.

Need Your Help

Searching Techniques Recommendations

search lucene full-text-search search-engine sphinx

This is more of a theory question rather than practice. I'm working on a project which is quite a simple catalog of links. The whole model is similar to the Dmoz or Yahoo catalog, except that each ...