2013-05-05 1 views
0

예를 들어, dummyLine = ACACACTA seqA에 문제가있는 경우와 같이 cout seqA를 수행합니다. 나는이 코드 이후에 seqA [lenA] 컴파일러에 쓸 때 배열의 차원을 결정해야하기 때문에 동적으로 배열에 임시 변수를 사용합니다. 출력의realloc 메모리가 C++에서 올바르게 작동하지 않습니다

char *seqA=NULL; 
char *temp=NULL; 
int lenA = 0; 

fileA.open("d:\\str1.fa"); 
if(fileA == NULL) { 
    perror ("Error opening 'str1.fa'\n"); 
    exit(EXIT_FAILURE); 
} 

string dummyLine; 
getline(fileA, dummyLine); 

while(getline(fileA, dummyLine)) { 
    lenA=lenA+(dummyLine.length()); 
    temp=(char*)realloc(seqA,lenA*sizeof(char)); 
    if (temp!=NULL) { 
     seqA=temp; 
     for (int i=0; i<(dummyLine.length()); i++) 
     { 
      seqA[lenA-dummyLine.length()+i]=dummyLine[i]; 
     } 
    } 
    else { 
     free (seqA); 
     puts ("Error (re)allocating memory"); 
     exit (1); 
    } 
} 

cout<<"Length seqA is: "<<lenA<<endl; 
cout<<seqA<<endl; 
fileA.close(); 

사진 : enter image description here

답변

2

문제는 당신이 seqA의 끝에 널 문자를 넣지 않는다는 것입니다.

realloc은 초기화되지 않은 메모리에 대한 포인터를 제공합니다. 그렇다면 dummyLine의 각 문자를 복사하지만 그 후에는 임의의 메모리가 있습니다. seqA 끝에 null 문자를 추가하여 유효한 C 문자열로 만드십시오.

염두에두고, null char이 자리 잡을 수있는 추가 문자를 temp=(char*)realloc(seqA,(lenA+1)*sizeof(char));에 추가해야합니다.

seqA[lenA-1] = '\0'; 
out<<seqA<<endl; 
3

이 코드를 읽는 것은 파일에서 모든 행을 읽고 단일 버퍼로 연결하려는 것입니다. 이렇게하려면 다른 문자열 객체를 사용해야합니다. 다음과 같음 : -

string dummyLine; 
string fileContents; 
getline(fileA, dummyLine); 

while(getline(fileA, dummyLine)) { 
    fileContents += dummyLine; 
} 

이렇게하면 std :: string이 모든 노력을 기울여 사용자가 할 필요가 없습니다. 너무 짧습니다.

+0

맞습니다. 내 생각에 코드를 사용하는 것이 가장 좋습니다. –

관련 문제