bitmapImage = malloc(Bi.biSizeImage);
Since I don't have your entire source program, I don't know whether anything else is wrong in the code that you show (or, especially, in the code that you don't show), but I think there is a Very Big Problem here:
The second parameter of f_read()
is a pointer to unsigned char, right? Its value will be the address of a region in memory where the information will be stored. [Edit](Maybe the function is defined with that parameter as a void pointer, but the function will use its value as a pointer to char when it copies the stuff.)[/Edit]
Anyhow, the second argument should be bitmapImage
, not &bitmapImage
See? the value of bitmapImage
is the address of the first element in your "dynamically allocated array," but &bitmapImage
is the address of the variable bitmapImage
, not the address of the beginning of the allocated region in memory.
The reason you might 'get away with it' if you use similar code for a declared array is that if you have something like the following.
Suppose you have
used by itself in an expression (without  brackets), is a pointer to uint8_t, and its value is the address of the first element of the array. The second argument in the call to f_read()
should be x
, not &x
In fact, since &x
is the pointer to an array, it happens that the value of &x
is the address of the first element of the array. Since &x
has the same numerical value as x
, this particular function "works." I think it's a Very Bad Thing to get into the habit of improper usage even though it apparently "works" in the case of arrays. Some compilers give a warning if you use the address of an array of char where a pointer to char should be used. If, however, the function's definition of the parameter was a void pointer, the compiler might not bail you out. You have to do it right.
And, of course, as NKurzman pointed out, you should always check the return value of malloc()
and its siblings to make sure it was successful (although I don't know what you should/can do about it if it fails).
That's why I try to avoid dynamic allocation where possible. I mean, if you are going to allocate this once and never free it, why not just use a declared array? And if you are going to free it, then, for goodness sake, return the value that malloc gave you so that you can deallocate it!
And, by the way, since you return after reading, but never do anything with the stored image and nothing outside that function can possibly know where it is, what's the point?
I have noted, from time to time, that source code in various Microchip distributions (as well as many examples of code from other sources) uses &x
for array arguments where x
should have been used. The code "works," but serves as a Very Bad Example that people should not copy.
post edited by davekw7x - 2017/12/07 11:34:12