gpt4 book ai didi

C++ 将 argv 读入 unsigned char 固定大小 : Segmentation fault

转载 作者:行者123 更新时间:2023-11-28 02:00:51 25 4
gpt4 key购买 nike

我正在尝试将命令行参数读入固定大小的无符号字符数组。我遇到段错误。

我的代码:

#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <memory.h>

unsigned char key[16]={};

int main(int argc, char** argv){
std::cout << "Hello!" << std::endl;
long a = atol(argv[1]);
std::cout << a << std::endl;
memcpy(key, (unsigned char*) a, sizeof key);
// std::cout << sizeof key << std::endl;
// for (int i = 0; i < 16; i++)
// std::cout << (int) (key[i]) << std::endl;
return 0;
}

我做错了什么?

调用程序:

编译:g++ main.cpp

执行:./a.out 128

最佳答案

您获得 SEGV 是因为您的地址错误:您将值转换为地址。加上大小是目的地之一,应该是源的大小

编译器发出警告,这不是好事,你应该考虑到它,因为那正是你的错误:

xxx.c:12:38: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]

memcpy(key, (unsigned char*) a, sizeof key);
^

像这样修复:

memcpy(key, &a, sizeof(a));

顺便说一句,您不必声明 16 个字节的 key。像这样分配它会更安全:

unsigned char key[sizeof(long)];

并且当您打印字节时,也要迭代直到 sizeof(long),否则您将在最后打印垃圾字节。

这是一个使用 uint64_t(来自 stdint.h 的无符号 64 位整数,它可以精确控制大小)的修复建议,对您的 键进行零初始化 并使用 strtoll 进行解析:

#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <memory.h>
#include <stdint.h>

unsigned char key[sizeof(uint64_t)]={0};

int main(int argc, char** argv){
std::cout << "Hello!" << std::endl;
uint64_t a = strtoll(argv[1],NULL,10);
memcpy(key, &a, sizeof a);

for (int i = 0; i < sizeof(key); i++)
std::cout << (int) (key[i]) << std::endl;
return 0;
}

(如果要处理signed,改成int64_t即可)

在小端架构上测试:

% a 10000000000000
Hello!
0
160
114
78
24
9
0
0

关于C++ 将 argv 读入 unsigned char 固定大小 : Segmentation fault,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39647682/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com