This might be expected but I'm just curious as to how/why this happens.
When i try to use a char *
declared locally char * foo = "\xFF\xFF..."
as an integer it seg faults. But if I use malloc it works perfectly well when i try to access it. Why does this happen?
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
unsigned char *buf = malloc(16);
memcpy(buf, "\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", 16);
//unsigned char *buf = "\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF"; // seg faults if you sue this instead
uint64_t *k = (uint64_t *) buf;
uint64_t *k2 = (uint64_t *) (buf + 8);
uint64_t i = 1000000000;
printf("-k =%" PRIu64 "\n", *k);
printf("-k2=%" PRIu64 "\n", *k2);
printf("Iter * %" PRIu64 "\n", i);
for (uint64_t c = 0; c < i; ++c)
{
*k += 1;
*k2 -= 1;
}
printf("-k =%" PRIu64 "\n", *k);
printf("-k2=%" PRIu64 "\n", *k2);
return 0;
}
Output:
easytiger $ gcc -std=c99 tar.c -Wall -O2 ; time ./a.out
-k =0
-k2=18446744073709551615
Iter * 1000000000
-k =1000000000
-k2=18446744072709551615