Re: low-level question



"Robert Gamble" <rgamble99@xxxxxxxxx> writes:
> jesso wrote:
>> I couldn't get this on a midterm. Darn!
>>
>> Anyone want to help?
>>
>> 1. Why does the following program output a 0?
>> 2. Explain in detail.
>> 3. How could you prevent this outcome without changing the code?
>>
>>
>> #include <stdio.h>
>> #include <string.h>
>>
>> int
>> main( int argc, char *argv[] )
>> {
>> int ii = 1;
>> char buf[ 4 ];
>>
>> strcpy( buf, "AAAA" );
>>
>> printf( "%d\n", ii );
>>
>> return 0;
>> }
>
> It is undefined behavior in C because you are writing past the end of
> an arry ("AAAA" is 5 characters, buf is 4). Since it is undefined
> behavior, anything can happen. There might be certain behaviors that
> are more likely to occur than others due to nuances of your specific
> platform but I can't think of anything plausible that would account for
> the behavior suggested by the question.

If ii is allocated just after the end of buf, and if the platform uses
a little-endian representation for int, the '\0' of "AAAA" could
plausibly be written over the low-order byte of ii, causing it to be
set to 0.

--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
.



Relevant Pages

  • Re: low-level question
    ... Darn! ... Why does the following program output a 0? ... > int ii = 1; ... This is still undefined behavior according to the ...
    (comp.lang.c)
  • low-level question
    ... Darn! ... Why does the following program output a 0? ... main(int argc, char *argv) ... char buf[4]; ...
    (comp.lang.c)
  • Re: Moving from C++ to VC++
    ... If it is the longest integer. ... platform, I want the longest integer type ... Now /I/ would like to have 'int' being the ... Adhering to what computing standards' intention ...
    (microsoft.public.vc.language)
  • Re: I2C bus implementation (for MPC82xx)
    ... > PowerMac (see the patches that just went in rewriting the PowerMac i2c ... > smbus API, but then, do you really want to use an existing i2c driver? ... For the resources I have used platform definition. ... +static int ...
    (Linux-Kernel)
  • Re: Using OleDBParameter in a simple UPDATE statement
    ... apparently the SQL commands via the .NET OleDb objects w/MySQL are required ... Actually that is specific to the underlying database you are ... Also you might already know this, but an int to one ... > platform might be not an int some other platform. ...
    (microsoft.public.dotnet.framework.adonet)