It's not a matter of 32-bit vs 64-bit, but an issue of using pointers which are not pointing to a valid memory address. In your code snippet, you have declared pointers *a
and *b
without actually pointing them anywhere, resulting in undefined behavior.
When using pointers always allocate immediately adequate memory, or point them to an existing corresponding variable.
For instance, all subsequent statements are valid:
int *a = NULL;
int *b = malloc(sizeof(int));
int c = 42;
int *d = &c;
By not initializing them, they are pointing to an arbitrary location. *a = 40;
has probably worked "by chance" for you, as it could had been pointing to a memory space where you had access at the time. But, in the general case, this snippet should produce a segmetation fault in either operating system.
If you are not planning to point a pointer immediately to a valid memory address, consider initializing it to NULL
, to avoid having a dangling pointer. You should never dereference a NULL
pointer, but you may always check whether a pointer is NULL
before attempting to do so. For example:
int *a = NULL;
if ( a != NULL ) {
*a = 42;
}
int *b = a;
if ( b != NULL ) {
printf("%d\n", *b);
}
This snippet won't print anything, as both *a
and *b
will be NULL
, but your code won't produce a segmentation fault.
For what is worth, I got a segmentation fault as well on a Debian 64-bit system.
[edited to integrate @AnT's, @tuple_cat's and @Weather Vane's feedbacks]