this question has answer here:
this might expected i'm curious how/why happens.
when try use char * declared locally char * foo = "\xff\xff..." integer seg faults. if use malloc works when try access it. why 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 sue instead uint64_t *k = (uint64_t *) buf; uint64_t *k2 = (uint64_t *) (buf + 8); uint64_t = 1000000000; printf("-k =%" priu64 "\n", *k); printf("-k2=%" priu64 "\n", *k2); printf("iter * %" priu64 "\n", i); (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
string literals immutable. may not modify data stored there. ever.
even in c nowadays make clear , diagnosable lobbing const pointer type.
c++ requires it.
Comments
Post a Comment