Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>That's pretty bad. Don't ever make a char buffer and cast it to a struct, because the alignment will be wrong (ie, the char buffer is going to have some random starting address because strings can start anywhere, but ints need/should have addresses multiples of four on most architectures).</p> <p>The solution is not to do nasty casts like that. Make a proper union that will have the alignment of the most restrictive of its members, or use a special element to force the alignment you need if you have to (see the definition of sockaddr_storage in your /usr/include/sys/socket.h or similar).</p> <h3>Illustration</h3> <p>You create a buffer on the stack and read some data into it:</p> <pre><code>char buf[1024]; int nread = read(fd, &amp;buf, sizeof(buf)); </code></pre> <p>Now you pretend the buffer was the struct:</p> <pre><code>CHECK(nread &gt;= sizeof(struct icmphdr)); struct icmphdr* hdr = (struct icmphdr*)buf; hdr-&gt;u.gateway; // probable SIGSEGV on eg Itanium! </code></pre> <p>By reinterpreting the buffer as a struct, we bypassed the compiler's checks. If we're unlucky, <code>&amp;hdr-&gt;u.gateway</code> won't be a multiple of four, and accessing it as an integer will barf on some platforms.</p> <h3>Illustration of solution</h3> <pre><code>strut iphdr hdr; int nread = read(fd, &amp;hdr, sizeof(hdr)); CHECK(nread == sizeof(hdr)); hdr.u.gateway; // OK </code></pre> <p>Let the compiler help you. Don't do grotty casts. When you make a buffer, tell the compiler what you're going to use the buffer for so it can put it in the correct place in memory for you.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload