[英]c++ reading argv into unsigned char fixed size: Segmentation fault
我正在嘗試將命令行參數讀入固定大小的無符號字符數組。 我遇到細分錯誤。
我的代碼:
#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位整數,可以精確控制大小)的修復建議, key
初始化為零,並使用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;
}
(如果要處理簽名,只需更改為int64_t
)
在小端架構上測試:
% a 10000000000000
Hello!
0
160
114
78
24
9
0
0
看來您正在復制太多數據。 我還為memcpy添加了&a。
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <memory.h>
unsigned char key[16]={};
int main(int argc, char** argv)
{
memset(key,0x0, sizeof(key));
std::cout << "Hello!" << std::endl;
long a = atol(argv[1]);
std::cout << a << std::endl;
// the size parameter needs to be the size of a
// or the lesser of the size of key and a
memcpy(key,(void *) &a, sizeof(a));
std::cout << "size of key " << sizeof(key) << "\n";
std::cout << "key " << key << "\n";
for (int i = 0; i < 16; i++)
std::cout << " " << i << " '" << ((int) key[i]) << "'\n";
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.