littlefs icon indicating copy to clipboard operation
littlefs copied to clipboard

Do not call lfs_free if the buffer to free is NULL

Open cdesjardins opened this issue 3 years ago • 4 comments

This can happen if lfs_malloc fails, or if the file doesn't exist, all "goto cleanup" clauses before and including the the lfs_malloc will cause this.

cdesjardins avatar Feb 08 '23 12:02 cdesjardins

This can happen if lfs_malloc fails, or if the file doesn't exist, all "goto cleanup" clauses before and including the the lfs_malloc will cause this.

Can this be triggered in a unit test, or would a malloc fail somehow have to be provoked?

vonj avatar Feb 08 '23 12:02 vonj

Please note my comment in this discussion: free with NULL is a no-op. Only thing that littlefs should guarantee is to properly initialize all its memory so unset pointers are NULL instead of random values..

BenBE avatar Feb 08 '23 13:02 BenBE

I suggest this pull request be closed in lieu of #790 that I just created. @cdesjardins, nothing personal, I've just been procrastinating after my discussion with @BenBE and just now managed to create a PR that addresses the same issue. I also covered the lfs_deinit() function in my PR which I believe covers all uses the lfs_free().

evpopov avatar Mar 29 '23 18:03 evpopov

It's worth noting @cdesjardins's case is a bit different from #790, since the case of the "goto cleanup" in lfs_file_open can be reached in normal operation.

That being said, as @BenBE points out, free with NULL is usually a no-op, and is guaranteed to be so in a standard-conforming stdlib.

And, if free does not support NULL, the lfs_free function is under user control if they create their own lfs_util.h file. I believe this would be the correct place to add such a NULL check.

geky avatar Apr 18 '23 01:04 geky