堆栈上的char数组导致seg错误

eas*_*ger 1 c arrays malloc

这可能是预期的,但我只是好奇如何/为什么会发生这种情况.

当我尝试使用char *声明的本地char * foo = "\xFF\xFF..."作为整数时,它会出错.但是,如果我使用malloc,当我尝试访问它时,它可以很好地工作.为什么会这样?

#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;

}
Run Code Online (Sandbox Code Playgroud)

输出:

easytiger $ gcc -std=c99 tar.c -Wall -O2 ; time ./a.out
-k =0
-k2=18446744073709551615
Iter * 1000000000
-k =1000000000
-k2=18446744072709551615
Run Code Online (Sandbox Code Playgroud)

Lig*_*ica 5

字符串文字是不可变的.您可能无法修改存储在那里的数据.永远.

现在即使在C语言中,我们通过const将指针类型转换为指针类型来使其清晰可辨.

C++实际上需要它.