milad_b
milad_b

Reputation: 197

realloc memory can't work correctly in C++

when i perform cout seqA, for example if dummyLine=ACACACTA seqA has problem. i use temp for dynamically array because when after this code i write seqA[lenA] compiler said that dimension of array must be determined.

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();

picture of output: enter image description here

Upvotes: 0

Views: 120

Answers (2)

DrYap
DrYap

Reputation: 6647

The problem is that you don't put a null char on the end of seqA.

realloc will give you a pointer to some uninitialised memory. Then you copy each character from dummyLine but after that there is just random memory. Make sure you add a null character to the end of seqA to make it a valid C string.

With that in mind, you need to add an extra character in you allocation where the null char can sit temp=(char*)realloc(seqA,(lenA+1)*sizeof(char));.

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

Upvotes: 2

Stewart
Stewart

Reputation: 4028

My reading of this code is that you are trying to read all the lines from the file, and concatenate them into a single buffer. To do that, you should just use another string object. Something like:-

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

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

This will let std::string do all of the hard work so that you don't have to. Much shorter too.

Upvotes: 3

Related Questions