Prev NEXT

The Basics of C Programming

Special Note on Strings

Special Note on String Constants

Suppose you create the following two code fragments and run them:

Fragment 1

{
    char *s;

    s="hello";
    printf("%s\n",s);
}

Fragment 2

{
    char s[100];

    strcpy(s,"hello");
    printf("%s\n",s);
}

These two fragments produce the same output, but their internal behavior is quite different. In fragment 2, you cannot say s="hello";. To understand the differences, you have to understand how the string constant table works in C.

Advertisement

When your program is compiled, the compiler forms the object code file, which contains your machine code and a table of all the string constants declared in the program. In fragment 1, the statement s="hello"; causes s to point to the address of the string hello in the string constant table. Since this string is in the string constant table, and therefore technically a part of the executable code, you cannot modify it. You can only point to it and use it in a read-only manner.

In fragment 2, the string hello also exists in the constant table, so you can copy it into the array of characters named s. Since s is not a pointer, the statement s="hello"; will not work in fragment 2. It will not even compile.

Special Note on Using Strings with malloc

Suppose you write the following program:

int main()
{
    char *s;

    s=(char *) malloc (100);
    s="hello";
    free(s);
    return 0;
}

It compiles properly, but gives a segmentation fault at the free line when you run it. The malloc line allocates a block 100 bytes long and points s at it, but now the s="hello"; line is a problem. It is syntactically correct because s is a pointer; however, when s="hello"; is executed, s points to the string in the string constant table and the allocated block is orphaned. Since s is pointing into the string constant table, the string cannot be changed; free fails because it cannot deallocate a block in an executable region.

The correct code follows:

int main()
{
    char *s;
    s=(char *) malloc (100);
    strcpy(s,"hello");
    free(s);
    return 0;
}