Wide string libc functions on unaligned memory

江枫思渺然 提交于 2021-02-11 12:12:40

问题


So I've discovered after painful debugging that libc functions like wcslen will fail silently when dealing with non memory-aligned buffers. In my case doing a wcslen( mystr ) resulted in a faulty length value, which only later on produced a crash (in wcstombs, assert buff[-1] == 0).

One solution would be for me to re-write all the wide string functions I need to work on non-aligned memory. This is easy enough but also dirty, and since there is not doc about which parts of libc support non memory aligned buffers, I'm afraid the problem is going to crop up again somewhere else.

Ensuring all my pointers are aligned is not an easy option since I deal with a lot of sub-buffer buffers and having to do manual copy of my data outside of the main buffer would take a long time. As an example, in my case the type of operation that fails is when I crawl (loop over) bytes in a large buffer looking for a wide string and then calculate the length.

Since I don't plan on needing to support too many platforms where pointer memory alignment is a deal-breaker (crash), is there any other solution? A compiler flag perhaps?

I know some platforms or environments require memory alignment, but I'm dealing with basic Windows and Linux UserMode, so please no "preachy" answers like "you're doing it wrong, you must always align everything" unless you have an actual solution, thank you.


回答1:


Well, the C and POSIX standard both mandate standard alignment, so if you forcefeed misaligned pointers into functions, you are violating the contract.

Therefore I doubt you can convince the library maintainers to see that as a bug.

Further, I think a feature request for broadening the contract won't get much traction.

Thus in the end, my best and final advice is: Code your own, and explicitly mark your pointers as misaligned. Maybe check alignment and delegate to the standard implementation at the start of each function, where appropriate for best speed...

I don't think you need any of the complex functions for your potentially misaligned data, so code away.



来源:https://stackoverflow.com/questions/22268475/wide-string-libc-functions-on-unaligned-memory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!