[問題] function用char**當參數

看板C_and_CPP作者 (wong0101)時間7年前 (2018/04/21 15:57), 7年前編輯推噓6(6012)
留言18則, 4人參與, 7年前最新討論串1/1
想請問板上的大大一個問題 下面有一段code, func2()是別人開的API, 我在func1()目前這樣實作看起來正常, 但是想釐清這樣寫會不會有潛在的記憶體問題? (1) 在messages從func1傳到func2時 因為沒有malloc記憶體給messages,導致在func2存取時發生奇怪行為? (2) 在messages[0] = s1.toLocal8Bit()時 沒有將s1.toLocal8Bit()的值存起來, 而是讓messages[0]指到一個有可能被覆蓋的記憶體空間? (3) 其他? 先謝謝各位了 void func1 ( const QString& s1, const QString& s2 ) { const char* messages[2]; // convert QString to char * messages[0] = s1.toLocal8Bit(); messages[1] = s2.toLocal8Bit(); func2( 2, messages ); } void func2 ( const int num_messages, const char ** messages ) { // do something } -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 42.73.134.127 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1524297430.A.C39.html ※ 編輯: wong0101 (42.73.134.127), 04/21/2018 15:58:20

04/21 16:42, 7年前 , 1F
目前自己的想法是(1)因為messages還會在stack中所以還是
04/21 16:42, 1F

04/21 16:44, 7年前 , 2F
可以在func2中被存取的,(2)messages[0]指到的位置應該會
04/21 16:44, 2F

04/21 16:45, 7年前 , 3F
有機會被蓋掉,導致奇怪的問題
04/21 16:45, 3F

04/21 17:33, 7年前 , 4F
應該純粹就是因為func1的messages是個矩陣,本身就是
04/21 17:33, 4F

04/21 17:35, 7年前 , 5F
pointer,宣告成pointer的pointer,所以才這樣子傳遞參
04/21 17:35, 5F

04/21 17:35, 7年前 , 6F
數的~
04/21 17:35, 6F

04/21 17:41, 7年前 , 7F
1)不會 2)會,QByteArray在toLocal8Bit()那行結束的時
04/21 17:41, 7F

04/21 17:41, 7年前 , 8F
候就destruct掉了
04/21 17:41, 8F

04/21 17:54, 7年前 , 9F
qt不熟,但是只要func1傳入的字串被釋放記憶體前,都不
04/21 17:54, 9F

04/21 17:55, 7年前 , 10F
會有問題,大家指到的位置都是s1,s2存放內容的矩陣位置
04/21 17:55, 10F

04/21 18:02, 7年前 , 11F
toLocal8Bit()會生一個暫時物件(QByteArray)出來
04/21 18:02, 11F

04/21 18:03, 7年前 , 12F
沒搞錯的話這邊會copy一份 然後馬上被destruct
04/21 18:03, 12F

04/21 18:03, 7年前 , 13F
messages指到的是一塊被free掉的memory
04/21 18:03, 13F

04/21 18:08, 7年前 , 14F
了解~
04/21 18:08, 14F

04/21 18:08, 7年前 , 15F
啊 正確來說不是copy, 是encode
04/21 18:08, 15F

04/21 18:09, 7年前 , 16F
toLocal8Bit 明明就回傳 QByteArray 你為什麼不乖乖接
04/21 18:09, 16F

04/21 18:09, 7年前 , 17F
總之不會跟QString共用空間
04/21 18:09, 17F

04/22 02:19, 7年前 , 18F
了解 感謝各位大大的指導!
04/22 02:19, 18F
文章代碼(AID): #1QskxMmv (C_and_CPP)