[Solved] why using sizeof in malloc?

sizeof doesn’t return the size of the memory block that was allocated (C does NOT have a standard way to get that information); it returns the size of the operand based on the operand’s type. Since your pointer is of type struct A*, the sizeof operand is of type struct A, so sizeof always returns … Read more

[Solved] Problem of a string read in function system() (probably due to a bad malloc) [closed]

chain1 = (char *) malloc(5*sizeof(char*) + 1); This will allocate enough space for five character pointers plus an extra byte. A pointer is not the same as a character, it tends to be either four or eight bytes currently but can actually be any size. You probably want sizeof(char) but, since that’s always 1, you … Read more

(Solved) Do I cast the result of malloc?

TL;DR int *sieve = (int *) malloc(sizeof(int) * length); has two problems. The cast and that you’re using the type instead of variable as argument for sizeof. Instead, do like this: int *sieve = malloc(sizeof *sieve * length); Long version No; you don’t cast the result, since: It is unnecessary, as void * is automatically … Read more