Monday, March 9, 2015

Autoconf does not work

I have a sample project, call

autoconf
./configure
sudo make  install

worked profectly.

I copy every thing, and create my own project.

meet some issues. autoconf not work properly.

Here are the issues I met:

1:  undefined macro am_init_automake.

run aclocal  first , fix this problme


2:  ./configuration missing  makefile.in.

the makefile.in did not generate properly.

I compare everything with sample project and mine.  finally,  I found there are two files, I did not create correctly.

1 NEWS   file is missing , even it is a empty file.
2 README  file is missing, I put it in parent folder.

When I create these 2 files.

3:  configure.ac
Makefile.am
end of line:
\r\n  should be \n

The third one is important.


automake work's fine.

but it should run script as  below:

aclocal
autoconf
autoreconf -vif
./configure
sudo make  install

Tuesday, March 3, 2015

How to properly malloc for array of struct in C

What's the difference between

struct mystruct *ptr = (struct test *)malloc(n*sizeof(struct test));
and

struct mystruct **ptr = (struct test *)malloc(n*sizeof(struct test *));
They both work fine, I'm just curious about the actual difference between the two. Does the first one allocate an array of structs, whereas the second one an array of struct pointers? The other way around? Also, which one has a smaller memory footprint?


The first allocates an array of struct, and the other allocates an array of pointers to struct. In the first case, you can write to fields by assigning ptr[0].field1 = value; right away, while in the second case you must allocate the struct itself before doing the actual writing.

It is OK to drop the cast of malloc result in C, so you could write

struct mystruct **ptr = malloc(n*sizeof(struct test *));
for (int i = 0; i != n ; i++) {
    ptr[i] = malloc(sizeof(struct test));
}
ptr[0]->field1 = value;
...
// Do not forget to free the memory when you are done:
for (int i = 0; i != n ; i++) {
    free(ptr[i]);
}
free(ptr);