- 论坛徽章:
- 0
|
我写了一段代码,过程大概是这样的:
打开一个文件,加密一个字符串, 将加密数据的长度和加密数据写入文件,
写入的秩序是先写入长度(长度为一字节),后写入数据;然后再文件偏移量移到文件开始的位置,
先读取长度,然后按长度读出加密数据。以下是大致的代码:
- static int __crypt_wstr( int fd, xso::isymmetric_cipher* cipher, const char* str )
- {
- int len = strlen( str );
- uint8_t* ctext = cipher->encrypt( str, &len );
-
- if ( NULL == ctext ) return -1;
-
- uint8_t tmp_len = len;
- int nbytes = write( fd, &tmp_len, 1 );
-
- if ( -1 == nbytes || 1 != nbytes ) {
- free( ctext );
- return -1;
- }
-
- nbytes = write( fd, &ctext, len );
-
- free( ctext );
- ctext = NULL;
-
- return ( -1 != nbytes && len == nbytes ) ? ( 0 ) : ( -1 );
- }
- static int __crypt_rstr( int fd, xso::isymmetric_cipher* cipher, char** buf )
- {
- uint8_t buf_len = 0;
- int nbytes = read( fd, &buf_len, 1 );
-
- printf( "buf_len=%d\n", buf_len );
-
- if ( -1 == nbytes || 1 != nbytes ) return -1;
-
-
- int len = buf_len;
-
- uint8_t* tmp = (uint8_t*)malloc( len );
-
- printf( "tmp=%p\n", tmp );
-
- if ( NULL == tmp ) return -1;
-
-
- nbytes = read( fd, &tmp, len );
-
- printf( "tmp=%p\n", tmp );
-
- if ( -1 == nbytes || len != nbytes ) {
- free( tmp );
- return -1;
- }
-
-
- *buf = (char*)cipher->decrypt( tmp, &len );
-
- if ( NULL == *buf ) {
- free( tmp );
- return -1;
- }
-
- free( tmp );
-
- *buf[len] = '\0';
-
- return 0;
- }
- int fd = open( "a", O_RDWR | O_CREAT, S_IRWXU );
-
- if ( -1 == fd ) {
- free( fp );
- printf( "open error: %s\n", strerror( errno ) );
- return;
- }
-
- free( fp );
-
-
-
- if ( -1 == __crypt_wstr( fd, &c, "abcdef" ) ) {
- close( fd );
- return;
- }
-
- if ( -1 == lseek( fd, SEEK_SET, 0 ) ) {
- close( fd );
- printf( "lseek error: %s\n", strerror( errno ) );
- return;
- }
-
- char* pt = NULL;
-
- if ( -1 == __crypt_rstr( fd, &c, &pt ) ) {
- close( fd );
- return;
- }
复制代码 问题出在__crypt_rstr函数中, 读出数据长度,动态分配tmp,
将数据read到tmp后,tmp的地址被改变,导致接下来一系列
内存访问错误。
请问原因是什么?怎么解决这个问题?多谢!
|
|