Search code examples
carrayspointersgccinitialization

Initialize array/block of data in C efficiently


I was trying to initialize an array in C and for each element GCC is generating a mov instruction(which is an inefficient approach if there are many elements to be initialized). How will I load memory with array data and return a pointer from it instead of initializing this way ?

6:array.c       ****         int a[]={1,2,3,4,5,9};
26                      .loc 1 6 0
27 0008 C745E001        movl    $1, -32(%rbp)
27      000000
28 000f C745E402        movl    $2, -28(%rbp)
28      000000
29 0016 C745E803        movl    $3, -24(%rbp)
29      000000
30 001d C745EC04        movl    $4, -20(%rbp)
30      000000
31 0024 C745F005        movl    $5, -16(%rbp)
31      000000
32 002b C745F409        movl    $9, -12(%rbp)
32      000000

Solution

  • I believe the following answers your question "How will I load memory with array data and return a pointer from it instead?":

    int a_data[] = {1,2,3,4,5,9};
    
    int main() {
      int *a = a_data;
    }
    

    This compiles to:

            .data
    a_data:
            .long   1
            .long   2
            .long   3
            .long   4
            .long   5
            .long   9
    
            .text
    main:
            .cfi_startproc
            pushq   %rbp
            .cfi_def_cfa_offset 16
            movq    %rsp, %rbp
            .cfi_offset 6, -16
            .cfi_def_cfa_register 6
            movq    $a_data, -8(%rbp)
            leave
            ret
            .cfi_endproc
    

    As you can see, the values live on the data segment, and main() simply takes a pointer to the data.

    Of course, if you mutate a[], these mutations will still be there next time you take the address of a_data. If you expect to get the original values, you should be making a copy of a_data, not simply using a pointer to it.