Why does POSIX contradict the ISO C standards [closed]

痴心易碎 提交于 2019-12-04 02:01:41

问题


See http://pubs.opengroup.org/onlinepubs/009696699/basedefs/sys/socket.h.html

(http://pubs.opengroup.org/onlinepubs/9699919799 is from Issue 7 - from 2013 and still the same!)

sockaddr_storage is meant to be cast to other structure types, but that contradicts the ANSI and ISO C standards aliasing rules as far as I can tell. (Objects may not be accessed through pointers to incompatible types, with the exception that anything can be accessed through the 3 char types and that the structure and its first member are interchangeable.)

I know that that practice of working with sockets existed long before C was standardised, but POSIX is supposed to conform to ISO C and actually it contradicts the standards in its manual. (Even in the newer versions of POSIX.)

Why did they make it like this in the first place? Why didn't they change it?


回答1:


The strict-aliasing rules in the standard constrain user code, not implementation code. Since the POSIX headers and libraries are part of the implementation, there is no actual conflict between the POSIX and the C standard.

In an open-source platform, and in particular in Linux where the C library and compiler are developed by different teams, this makes life difficult for implementors, but that is their concern, not yours. For example, the implementors could:

  • refrain from exposing the potential conflict between the standards (that is, disable strict-aliasing optimizations);
  • admit that their implementation is not POSIX compliant (and note that, for example, there are no POSIX-certified Linux distributions);
  • provide facilities to ensure that the potentially conflicting facilities do not actually conflict. From the point of view of the C standard, this would be an extension.

This last option is how the gcc and glibc teams are working to resolve the sockaddr issue; see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=71255




回答2:


As a matter of fact, I do not think there is a violation of strict aliasing rule here. Yes, you cast it to a different type when you call a function, but who said it has to be accessed through pointer of this type?

Protocol implementations know the proper type of the structure, so when they access the structure, they convert it back to the proper type. Conversion here is only used for passing pointer from one routine to another, but converted type is not used to access the data.



来源:https://stackoverflow.com/questions/37661031/why-does-posix-contradict-the-iso-c-standards

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