Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing of string literals in consecutive memory locations

    #include <stdio.h>
    #include <string.h>
    int main() {

    char *s[] = {"cricket","tennis","football"};

    printf(" String are: \n\n");
    printf("  %s \n", *(s));
    printf("  %s \n", *(s+1));
    printf("  %s \n", *(s+2));
    printf("  \n\n");

    printf("  Starting locations of the string are: \n\n");

    printf("  %d\n",*(s));
    printf("  %d\n",*(s+1));
    printf("  %d\n",*(s+2));
    printf("  \n\n");

    return 0;
}

OUTPUT:

String are: 

cricket 
tennis 
football 


Starting locations of the string are: 

134514112
134514120
134514127

s is a array of character pointers. s has three elements and each of them are storing the starting address of the string literals.i.e. s[0] is a pointer pointing to the starting address of "cricket". etc..

My question is :

By observing these addresses we can see that second string is stored just after the null character of the first string. All three strings are stored in sequential form. Is this always true ?

like image 750
Debashish Avatar asked Aug 17 '16 12:08

Debashish


Video Answer


2 Answers

This is a linker decision - to store string literals tightly or not. There is no guaranties. Or even this may be done by compiler - it may create continuous data section that holds all involved literals. But nevertheless actual layout of that section is still implementation-specific and you shouldn't assume anything about it.

like image 187
Sergio Avatar answered Sep 18 '22 01:09

Sergio


I have an example for you:

#include <stdio.h>
#include <inttypes.h>

char    *s[] = { "ball", "football" };

int main( void ) 
{
    int i;

    for( i=0; i<2; i++ ) {
        printf( "%" PRIuPTR "\n", (uintptr_t)s[i] );
        // or printf( "%p\n", s[i] ); forr hex output
    }
}

If I compile and run that program with gcc -O3 I get:

4195869
4195865

What happens here is that the optimizer merges both string literal to a single "football" so that s[0] becomes s[1] + 4.

That's only one example of what compiler / linker might decide on how to store string literals ...

like image 23
Ingo Leonhardt Avatar answered Sep 19 '22 01:09

Ingo Leonhardt