2017-03-23 82 views
0

第一本我的代碼iOS的一個很神奇(malloc_error_break)

#pragma pack (4) 
typedef struct _Login{ 
char user[32]; 
char pwd[32]; 
int userID; 
}Login,*PLogin; 

const unsigned long MSG_TAG_HEADER_YXHY = 0x59485859; 

#pragma pack (2) 

typedef struct tagTcpPacketHeader 
{ 
    int  ulHtag; 
    char ucVersion; 
    char ucCmd; 
    int  ulUserId; 
    short usPacketNum; 
    int  ulDataLen; 
}TcpPacketHeader,*LPTcpPacketHeader; 
#pragma pack() 

const unsigned int TCP_HEADER_PACKET_LEN = sizeof(TcpPacketHeader); 

- (NSData*)sendDataFileWithUserId:(const int)nUserId nCmd:(const int)nCmd pData:(NSData*)data{ 

    NSData* sendData; 
    void* sendObj = malloc(data.length); 
    [data getBytes:sendObj length:data.length]; 
    static int nPacketNum = 0; 
    int nLen = (int)data.length + TCP_HEADER_PACKET_LEN; 
    char *pTmpBuf = malloc(nLen); 
    LPTcpPacketHeader tcpHeader = (LPTcpPacketHeader)pTmpBuf; 
    tcpHeader->ulHtag = MSG_TAG_HEADER_YXHY; 
    tcpHeader->ucVersion = 1; 
    tcpHeader->ucCmd = nCmd; 
    tcpHeader->ulUserId = nUserId; 
    tcpHeader->usPacketNum = nPacketNum; 
    tcpHeader->ulDataLen = nLen; 
    memcpy(tcpHeader + TCP_HEADER_PACKET_LEN,sendObj, data.length); 
    sendData = [NSData dataWithBytes:pTmpBuf length:nLen]; 
    nPacketNum++; 
    free(pTmpBuf); 
    free(sendObj); 
    return sendData; 
} 

- (NSData*)get_File_Login:(NSString*)userID{ 
    int length = sizeof(Login); 
    Login log_in = {"123","456",userID.intValue}; 
    NSData* login_data = [NSData dataWithBytes:&log_in length:length]; 
    NSData* ret = [self sendDataFileWithUserId:log_in.userID nCmd:5 pData:login_data]; 
    return ret; 
} 

使用

NSData* ms = [self get_File_Login:@"123"]; 
    NSLog(@"%@",ms); 

頻繁使用後,可能會出現問題

question

這個問題讓我很頭疼,爲什麼會出現「設置malloc_error_break斷點調試」 我已經加入了「malloc_error_break」斷點,但它不工作...... 誰能告訴我答案???

+0

更改memcpy使用'pTmpBuf'而不是'tcpHeader'作爲指針,它有幫助嗎? –

+0

問題解決了,這是問題的類型,非常感謝! B(¯▽¯)d – FixBugProgrammer

回答

0

當您使用的memcpy的指針這樣

memcpy(tcpHeader + TCP_HEADER_PACKET_LEN,sendObj, data.length); 

,這意味着要複製到由數據的大小tcpHeaderTCP_HEADER_PACKET_LEN倍指針Po指向內存位置整理到。這與做&tcpHeader[TCP_HEADER_PACKET_LEN]是一樣的。

假設你想要寫頭之後有兩種方法來解決它的位置:

1)使用指針的大小爲1,意味着一個char*。在你的代碼有一個指針pTmpBuf就是這樣所以纔將代碼更改爲:

memcpy(pTmpBuf + TCP_HEADER_PACKET_LEN, sendObj, data.length); 

2)使用尺寸1這種計算。由於數據的它所指向的大小是一樣的TCP_HEADER_PACKET_LEN然後通過一個乘以它提供了正確的位置:

memcpy(tcpHeader + 1, sendObj, data.length); 

我建議第一,因爲很明顯你是什麼計算。在第二種情況下,您不清楚爲什麼要添加一個,以及在複製非該類型的數據時使用指向一種類型的指針。