1
#include<stdio.h>
#include<stdlib.h>

static char mem[4];

int main()
{
    int* A = (int*)(mem);

    mem[0] = 0;
    mem[1] = 1;
    mem[2] = 2;
    mem[3] = 3;

    int i;
    A[0] = 5;

    for (i = 0; i<4; i++)
    {
        printf("%d\t", mem[i]);
    }

    printf("\n");
    return 0;
}

My question is, why does this print 5 0 0 0 rather than 5 1 2 3? Why is the array "wiped out?"

5
  • 4
    char and int don't have the same sizes. writing the first element of A writes all 4 elements of mem Feb 15, 2018 at 19:51
  • 6
    Because you wrote code the violates language constraints, and got yourself some undefined behavior. Feb 15, 2018 at 19:52
  • 1
    replace with A[0] = 123456789; to make it more intuitively understandable.
    – Rotem
    Feb 15, 2018 at 19:53
  • int* A = (int*)(mem); --> risks undefined behavior per "If the resulting pointer is not correctly aligned for the referenced type, the behavior is undefined." C11dr §6.3.2.3 7 Feb 15, 2018 at 20:54
  • Congratulations, you've discovered little-endian storage. Feb 15, 2018 at 21:04

4 Answers 4

6

in your case

A[0] = 5;

writes 5 as integer which has a bigger size than char (2,4,8, depends).

Your system seems to be little endian, so 5 is written in the first char location, then zeroes.

note that if sizeof(int) is 8 (as it can happen on some systems), your code is unsafe and triggers undefined behaviour as it overwrites memory past the mem array (not to mention possible misalignment issues that may slow down operatons or even crash on some processors)

Which is why we must respect the strict aliasing rule to avoid "lying to the compiler", for instance, create an union so the compiler can adjust alignment & check sizes.

This other Q&A is related: What happens when you cast a char * address to int * in C when the address is not word-aligned?

11
  • 1
    I am curious; I normally don't write code like this. Is this a violation of the strict aliasing rule?
    – machine_1
    Feb 15, 2018 at 19:55
  • 4
    @ZanLynx - It doesn't look like one, it is one. You can use a char* to access any object type. You may not use an int* to access an object declared as char[4]. It's not the same. Feb 15, 2018 at 20:14
  • 2
    @ZanLynx - I call it undefined behavior. An implementation is allowed to make it defined, but it's not ISO C that makes it okay Feb 15, 2018 at 20:27
  • 2
    @ZanLynx - Access by a character type, and the object having a character (array) type, is not the same thing. The OP does access via an int type when they write 5. Feb 15, 2018 at 20:41
  • 2
    @ZanLynx: A[0]=5 does not “write bytes into the character array.” In the terminology of the C standard, it access the objects of the array of char through an lvalue of type int, and this is expressly prohibited by C 2011 (N1570) 6.5 7. Feb 15, 2018 at 21:00
2

Because in your system sizeof int is atleast 4 times that of sizeof(char) so it took 4 bytes to overwrite all that you wrote because A is a pointer to int.(But it can take larger than that) (This is the case that would typically be) In case it is not it is an undefined behavior.

Also note in mind that how we write it is depending upon the endianness. In your case it is little endian. So based on endianness it might differ also. No matter what this has no more than experimental purpose.

Also to give you an idea why it is UB when sizeof(int) is greater than 4 - is then you would access via A[0] some meory out of this array memory and try to modify it and make changes to it - leading to undefined behavior.

4
  • Could be 4 or 8, OP is probably on a LE system so they'd both give 5.
    – Kevin
    Feb 15, 2018 at 19:53
  • It's at least 4. The OP didn't print more than the first 4, so we can't really know. A nitpick, but still Feb 15, 2018 at 19:53
  • @StoryTeller.: Yes. I edited that. In case it is mpre than 4 it's UB. Feb 15, 2018 at 19:54
  • @StoryTeller.: Was looking for standard - earlier comment was missing the point saying that I edited. Correct me if there is any major issue or even importantly any minor one. Feb 15, 2018 at 20:06
2

Your code exhibits undefined behavior, as you try to alias char * type using an int pointer. It is a violation of the strict aliasing rule, so your code is simply erroneous.

A char * type may alias other pointer types, but not the other way around. So, make sure not to violate the language's constraints.

0

int* A = (int*)(mem); --> risks undefined behavior per "If the resulting pointer is not correctly aligned for the referenced type, the behavior is undefined." C11dr §6.3.2.3 7

So the rest of code is moot.

Use a union to cope with alignment and anti-aliasing concerns.

#include <stdio.h>

int main(void) {
  union {
    int i;
    unsigned char mem[sizeof(int)];
  } u;

  for (unsigned i = 0; i < sizeof(int); i++) {
    u.mem[i] = i;
    printf("%hhu\t", u.mem[i]);
  }
  printf("\n");

  u.i = 5;

  for (unsigned i = 0; i < sizeof(int); i++) {
    printf("%hhu\t", u.mem[i]);
  }
  printf("\n");
  return 0;
}

Output (may vary on your machine)

0   1   2   3   
5   0   0   0

Why: Now that undefined behavior UB is removed from the code, Jean-François Fabre good answer explains the differences.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.