[問題] memcpy出現segmentation fault

看板C_and_CPP作者 (走味的咖啡)時間9年前 (2014/10/09 17:28), 編輯推噓1(104)
留言5則, 3人參與, 最新討論串1/1
使用Dev-C++ 4.9.9.2做模擬, code如下: #include <stdio.h> #include <stdlib.h> #include <memory.h> #include <string.h> #include <stdlib.h> typedef unsigned char uint8_t; typedef struct { uint8_t flag; uint8_t *pData; } __attribute__ ((packed)) test_str; void copy_buf(test_str *pTest_inst, uint8_t *pBuf) { //segmentation fault memcpy(pTest_inst->pData, pBuf, 1); printf("%c ", *(pTest_inst->pData)); /*//Success uint8_t t[16]; memset(t, 0, sizeof(t)); memcpy(&t, pbuf, 1); pCosem->pData = t; printf("%c ", *(pCosem->pData)); */ } int main(int argc, char *argv[]) { uint8_t t[6] = "Hello"; test_str test_inst; memset(&test_inst, 0, sizeof(test_str)); copy_buf(&test_inst, t); system("PAUSE"); return 0; } 在copy_buf()函式裡的memcpy, 有按照正確型態輸入 但一直出現segmentation fault 後來嚐試用別的方法,宣告了一組實體陣列做temp是沒問題 但仍然是想知道為何一開始使用的方法會segmentation fault -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 203.74.125.49 ※ 文章網址: http://www.ptt.cc/bbs/C_and_CPP/M.1412846907.A.604.html

10/09 17:42, , 1F
test_inst = 0x0
10/09 17:42, 1F

10/09 17:42, , 2F
也沒有memory alloction
10/09 17:42, 2F

10/09 20:37, , 3F
pData 被你清成 NULL, memcpy 又要寫進 NULL...
10/09 20:37, 3F

10/09 20:38, , 4F
處理指標參數時最好做 null check
10/09 20:38, 4F

10/11 17:51, , 5F
要先malloc個位置給test_inst->pData
10/11 17:51, 5F
文章代碼(AID): #1KDbKxO4 (C_and_CPP)