[問題] structure一問

看板C_and_CPP作者 (有事來信)時間15年前 (2009/05/11 20:36), 編輯推噓4(4015)
留言19則, 6人參與, 最新討論串1/1
#include <stdio.h> #include <stdlib.h> #include <iostream> #include <string> #include <fstream> #include <sstream> using namespace std; typedef struct node { string name; int number; struct node* prev; struct node* link; } NODE; int main() { string geTmp; string strTmp; string inTmp; NODE* list; string filenameR = "phone.txt"; ifstream inFile; inFile.open(filenameR.c_str()); while( getline(inFile, geTmp) ) { list = (NODE*)malloc(sizeof(NODE)); stringstream token(geTmp); while(1) { token>>strTmp; if(token.fail()) { break; } list->name = strTmp; token>>inTmp; list->number = atoi( inTmp.c_str() ); cout<<list->number<<endl; cout<<strTmp<<endl; } } return 0; } 若將黃色的部份蓋掉 程式就不會出問題 覺得蠻怪的 把讀到東西存成string 然後assign給structure裡面的string data type一樣 卻會當掉....不知道原因為何ˊ ˋ" 請問有人能幫忙解惑嗎? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.113.243.94

05/11 20:44, , 1F
Use `operator new` instead of `malloc`
05/11 20:44, 1F

05/11 21:00, , 2F
好像還是會當...?
05/11 21:00, 2F

05/11 22:07, , 3F
好像?你試過了嗎?
05/11 22:07, 3F

05/11 22:15, , 4F
另外這支程式會 memory leak
05/11 22:15, 4F

05/11 22:17, , 5F
已經找到問題了,因為list是動態記憶體規畫,
05/11 22:17, 5F

05/11 22:18, , 6F
list->name 每次讀的字串大小不盡相同
05/11 22:18, 6F

05/11 22:18, , 7F
compile會過,但是程式跑會當掉。
05/11 22:18, 7F

05/12 11:15, , 8F
不知道你在說什麼, name 是 std::string,它的=operator
05/12 11:15, 8F

05/12 11:15, , 9F
根本就預計你會 assgin 不同長度的東西進去
05/12 11:15, 9F

05/12 13:27, , 10F
試過 會當
05/12 13:27, 10F

05/12 13:37, , 11F
你檔案多大?有釋放記憶體嗎?有檢查是否回傳NULL嗎?
05/12 13:37, 11F

05/12 21:28, , 12F
喔 會當,是吧
05/12 21:28, 12F

05/12 21:42, , 13F
我猜因為你看不懂一樓的解釋 所以就沒做了 於是另外猜測
05/12 21:42, 13F

05/12 21:55, , 14F
暫時有其他比較low的方法可以替代 加上作業有時效性
05/12 21:55, 14F

05/12 21:56, , 15F
我等忙完再來討論 ˊˋ"
05/12 21:56, 15F

05/12 21:57, , 16F
是看不懂一樓的建議沒錯 還沒去找語法
05/12 21:57, 16F

05/12 21:59, , 17F
一樓的意思是list = (NODE*)malloc(sizeof(NODE));
05/12 21:59, 17F

05/12 21:59, , 18F
改成list = new NODE;
05/12 21:59, 18F

05/12 22:01, , 19F
因為malloc只配置空間 所以裡面的std::string內容是亂的
05/12 22:01, 19F
文章代碼(AID): #1A21lZVI (C_and_CPP)