2016-09-22 23 views
0

我想读命令行参数到一个固定大小的无符号字符数组。我得到分段错误。c + +读取argv到无符号字符固定大小:分段错误

我的代码:

#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

+0

你的问题是不完整的。你怎么称呼你的程序? –

+0

你传递给了什么? – Raindrop7

+0

它可以是0到2^128之间的任何数字,对吗? – algoProg

回答

2

你得到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)); 

BTW你没有16个字节的申报key。这将是更安全的分配是这样的:

unsigned char key[sizeof(long)]; 

,并在打印的字节数,迭代,直到sizeof(long)过,或者你只是打印垃圾字节到底。

下面是使用uint64_t修复建议(64位无符号整数stdint.h这给大小精确控制),零初始化为您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 
+0

嗨,让,那是我的问题。我可以让它漫长吗? – algoProg

+0

@ 1201ProgramAlarm:不完全,你是对的,谢谢。我错过了从整数到地址的转换! –

+0

修复了它。没有更多的错误。我如何检查密钥的价值?我评论的打印循环不起作用。编译器打印'?'。 – algoProg

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