I\'m a total C newbie, I come from C#. I\'ve been learning about memory management and the malloc()
function. I\'ve also came across this code:
char
First point - it is a good habit to never put absolute numbers in the argument to malloc, always use sizeof and a multiple. As said above, the memory allocated for some types varies with compiler and platform. In order to guarantee gettin enough space for an array of type 'blob' it is best to use something like this:
blob *p_data = malloc(sizeof(blob) * length_of_array);
This way, whatever the type is, however it looks in memory you'll get exactly the right amount.
Secondly, segfaults etc. C, as a low level language, has no bounds checking. This means that there is nothing to check you are looking at an index not actually in the array. In fact it doesn't stop you accessing memory anywhere even if it doesn't belong to your program (although your operating system might, thats what a segfault is). This is why, whenever you pass an array around in C you need to pass its length as well, so that the function receiving the array knows how big it is. Don't forget that an 'array' is really just a pointer to the first element. This is very unhelpful when passing strings around - every string argument would become two arguments, so a cheat is used. Any standard C string is NULL terminated. The last character in the string should be ASCII value 0. Any string functions work along the array until they see that and then stop. This way they don't overrun the array, but if its not there for some reason, they will. That being understood
strlen("Hello")
is 5, but to store it you need one more character. E.g.:
const char str1 = "Hello";
char *str2 = malloc(sizeof(char) * (strlen(str1) + 1));
strcpy(str2, str1);
And yes, sizeof(char) is unnecessary because it is defined to be 1, but I find it clearer and it is definitely a good habit.