0

I have a serious problem with writing an App on Linux. I have this code

#include <stdio.h>

int main()
{
    char ar[10][10];
    strcpy(ar[1], "asd");
    strcpy(ar[2], "fgh");

    int test[2];
    test[1] = (int)ar[1];
    printf("%s %x | %s %x\n\n", ar[1], ar[1], test[1], test[1]);

    return 0;
}

And it works on Windows well, but when i want to run this on Linux i got Segmentation Fault or Unauthorized Access to memory.

Lukasas
  • 139
  • 8
  • 1
    Your program has *undefined behaviour* which basically means the program can do anything including *working as expected*. Read [Undefined Behavior and Sequence Points](http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points) and [What every C programmer should know about Undefined Behaviour](http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html) – P.P Oct 21 '14 at 21:35
  • @Blue: I don't see what sequence points have to do with this discussion; there is no undefined behavior here resulting from multiple modification of variables without intervening sequence points. – Billy ONeal Oct 21 '14 at 21:39

1 Answers1

3

Your program invokes undefined behavior. It assumes that a pointer will fit into an int, which isn't required. Usually pointers will fit on Unix boxes and fail on Windows; but you should use an appropriate integer type, such as intptr_t from stdint.h if you need to do such conversions. Note that strictly speaking the integer must be cast back to a pointer type before being passed to printf.

Using a pointer type to printf and a large enough integral type results in correct behavior: http://ideone.com/HLExMb

#include <stdio.h>
#include <stdint.h>

int main(void)
{
    char ar[10][10];
    strcpy(ar[1], "asd");
    strcpy(ar[2], "fgh");

    intptr_t test[2];
    test[1] = (intptr_t)ar[1];
    printf("%s %x | %s %x\n\n", ar[1], ar[1], (char*)test[1], (char*)test[1]);

    return 0;
}

Note though that casting pointers into integral types is generally frowned upon and is likely to result in program bugs. Don't go there unless you absolutely need to do so for one reason or another. When you're starting out in C it is unlikely that you'll ever need to do this.

Billy ONeal
  • 104,103
  • 58
  • 317
  • 552