I have always wondered about compound literals in C, do they create duplicate copies?
Take the following two examples for instance. The only difference between the two are few lines of code, respectively
book->book_id = book_id;
book->price = price;
book->isbn = isbn;
in the first example, and
*book = (Book) {
.book_id = book_id,
.price = price,
.isbn = isbn
};
in the second example.
My question is simple: Does the second example allocate a Book structure in the stack first and then copy it into the heap, or does the second example behave exactly like the first example, and simply populates the structure already allocated in the heap without touching the stack?
Example 1
#include <stdio.h>
#include <stdlib.h>
typedef struct Book_T {
unsigned int book_id;
unsigned int price;
long unsigned int isbn;
} Book;
Book * new_book (
const unsigned int book_id,
const unsigned int price,
const long unsigned int isbn
) {
Book * book = malloc(sizeof(Book));
if (!book) {
return NULL;
}
book->book_id = book_id;
book->price = price;
book->isbn = isbn;
return book;
}
int main (
const int argc,
const char * argv[]
) {
Book * my_book = new_book(12944, 39, 9783161484100);
if (!my_book) {
fprintf(stderr, "Error allocating memory\n");
return 1;
}
/* Do something with `my_book`... */
free(my_book);
return 0;
}
Example 2
#include <stdio.h>
#include <stdlib.h>
typedef struct Book_T {
unsigned int book_id;
unsigned int price;
long unsigned int isbn;
} Book;
Book * new_book (
const unsigned int book_id,
const unsigned int price,
const long unsigned int isbn
) {
Book * book = malloc(sizeof(Book));
if (!book) {
return NULL;
}
*book = (Book) {
.book_id = book_id,
.price = price,
.isbn = isbn
};
return book;
}
int main (
const int argc,
const char * argv[]
) {
Book * my_book = new_book(12944, 39, 9783161484100);
if (!my_book) {
fprintf(stderr, "Error allocating memory\n");
return 1;
}
/* Do something with `my_book`... */
free(my_book);
return 0;
}