Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Your problem is most probably pointer arithmetic.</p> <p><code>ino_table + i * sizeof(struct inode)</code></p> <p>is most probably not what you want, but </p> <p><code>ino_table + i</code></p> <p>as due to pointer arithmetic <code>ino_table + i</code> is already doing </p> <p><code>((char *)ino_table) + i * sizeof(struct inode)</code></p> <p>The same applies to gdb, where <code>ino_table + 8000</code> refers to <code>&amp;ino_table[8000]</code>- the 8000th element of <code>ino_table</code>, which, unless your struct inode is defined to be 1 byte in size, would be outside of the allocated memory.</p> <hr> <p><strong>More genericly speaking:</strong></p> <p><em><strong>If you have a pointer P to a type T, then P++ will increment the address stored in P by sizeof(T), and NOT by one byte.</em></strong></p> <hr> <p>Also, instead of</p> <p><code>ino_table + i</code></p> <p>you could do</p> <p><code>&amp;ino_table[i]</code></p> <p>which is preferred by many people (I personally don't really care) because it makes it more obvious that increasing <code>i</code> increases the accessed address by <strong>one element, and <em>not</em> one byte</strong>.</p> <hr> <p>And for the malloc you could do</p> <p><code>malloc(number_of_elements * sizeof(type))</code> - don't worry about performance difference or code size, as when number_of_elements is constant, the expression should be optimized into one constant number anyway.</p> <p>Or, if you wanna be extra-careful and/or don't know if you will access parts which you haven't written to, you could use:</p> <p><code>calloc(number_of_elements, sizeof(type))</code></p> <p>The difference to <code>malloc</code> is that <code>calloc</code> makes sure you get nulled memory (on most implementations by serving you a pointer to a special <em>copy-on-write</em> zeroed memory page of the system), as well as returning memory aligned to <code>sizeof(type)</code> (malloc will normally also return aligned memory, but in the case of malloc, it will probably be aligned to the largest alignable value)</p> <hr> <p>As bounds checking has been mentioned in a different answer: You could have a look at gcc <strong>mudflap</strong> extension - it doesn't exactly do bounds checking, but many other memory related things, and IMHO is one of the easiest things to set up besides <strong>valgrind</strong> (which doesn't need any setup, but unfortunately doesn't always work)</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