I always confuse about what to put inside of sizeof when malloc
for example,
struct sth *p = malloc(sizeof(struct sth));
or
struct sth *p = malloc(sizeof(struct sth *));
or, char ***p = malloc(sizeof(WHAT_SHOULD_I_PUT_HERE));
???
someday, some c guru told me that use the variable like this:
struct sth *p = malloc(sizeof(*p));
So i wrote some code:
void main() {
int n = 1000000, i;
char **p = malloc(sizeof(char *) * n); // works
//char **p = malloc(sizeof(**p) * n); // not work, segfault
for(i=0; i<n; i++) {
// p[i] = malloc(sizeof(char)); // works
// p[i] = malloc(sizeof(p[i])); // works
// p[i] = malloc(sizeof(*p[i])); // works
}
for(i=0; i<n; i++) {
free(p[i]);
}
free(p);
}
still get confused, any easy way to remember?