成功调用函数后中止陷阱6

时间:2014-09-03 14:48:54

标签: c pointers

我试图弄清楚为什么我会得到一个中止陷阱:6执行一个函数。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char *Asc2Hex(char *data, char *buffer);
char *Hex2Asc(char *data, char *buffer);

int main(void)
{
    char *convert = "546865206f6e652065796564206f6e6520686f726e656420666c79696e6720707572706c652070656f706c65206561746572206973206120667572727920707572706c65207075737379";
    char  buffer[sizeof(convert)*2]; 
    char *test = Hex2Asc(convert, buffer);
    printf("Data: %s\nSize: %lu bytes\n", test,strlen(test));
    return 0;
}

int hex_to_int(char c){
    if(c >=97)
        c=c-32;
    int first = c / 16 - 3;
    int second = c % 16;
    int result = first*10 + second;
    if(result > 9) result--;
    return result;}

int hex_to_ascii(char c, char d){
    int high = hex_to_int(c) * 16;
    int low = hex_to_int(d);
    return high+low;
}

char *Hex2Asc(char *data, char *buffer){
    int i, x, len = strlen(data);
    char buf = 0;
    for(i = 0,x = 0; i < len; i++){
        if(i % 2 != 0){
            sprintf(buffer+x,"%c",hex_to_ascii(buf,data[i]));
            x++;
        }else{
            buf = data[i];
        }
    }
    return buffer;
}

如果我将要转换的字符串传递给char convert [] = ...

,则不会发生中止陷阱6

即:

char convert[] = "546865206f6e652065796564206f6e6520686f726e656420666c79696e6720707572706c652070656f706c65206561746572206973206120667572727920707572706c65207075737379";

试图了解原因。这也会引起头疼,因为我需要能够获取指向字符数组的指针并将其传递给函数。我有另一个功能 - Asc2Hex - 它具有相同的问题(显然) - 因为它的编码基本相同。任何指针,没有双关语意图?

Process 23540 stopped
* thread #1: tid = 0xfc5ce9, 0x00007fff90e83866 libsystem_kernel.dylib`__pthread_kill + 10, queue = 'com.apple.main-thread', stop reason = signal SIGABRT
    frame #0: 0x00007fff90e83866 libsystem_kernel.dylib`__pthread_kill + 10
libsystem_kernel.dylib`__pthread_kill + 10:
-> 0x7fff90e83866:  jae    0x7fff90e83870            ; __pthread_kill + 20
   0x7fff90e83868:  movq   %rax, %rdi
   0x7fff90e8386b:  jmpq   0x7fff90e80175            ; cerror_nocancel
   0x7fff90e83870:  ret    
(lldb) c
Process 23540 resuming
Process 23540 exited with status = 0 (0x00000000) 
(lldb)

0 个答案:

没有答案