Home > Back-end >  For help! C language malloc and structure call causes error while reading the string of characters
For help! C language malloc and structure call causes error while reading the string of characters

Time:05-24

Turn to
 

Void ReadInputFile () {
The FILE * fp=fopen (inputFileName, "r");
//open input file
If (fp==NULL) {
Printf (" % s \ n "wrong, inputFileName);
system("pause");
The exit (2);
}
Char * data=https://bbs.csdn.net/topics/(char *) malloc (sizeof (char) * maxLen);
Int dataSize=0;
char ch;
While ((ch=fgetc (fp))! EOF)={
Data [dataSize]=ch;
DataSize++;
}
fclose(fp);
Data [dataSize]='\ 0';
FileData. Data=https://bbs.csdn.net/topics/data;
FileData. Size=dataSize;
Printf (" read success! \ n \ n ");
MyString * Filep=(MyString *) malloc (sizeof (MyString));
Filep - & gt; Size=dataSize.//content size
Filep - & gt; Data=https://bbs.csdn.net/topics/data;
Free (Filep);
Free (data);
Filep=data=https://bbs.csdn.net/topics/NULL;
}

Typedef struct MyString {
Unsigned char * data;
Int size;
} MyString.




CodePudding user response:

Unsigned char * data; This also want to allocate memory to store data

CodePudding user response:

Debugging code necessary knowledge: to what say what words,
Don't expect to see as a result, when I was just to perform a

CodePudding user response:

Code is not complete, so only from your existing code to ponder, fileData is a global variable? In ReadInputFile function, read files, fileData. Data=https://bbs.csdn.net/topics/data, original intention is to through the fileData will read the data back? But behind the ReadInputFile there is free (data), data (and fileData. Data) to store is released, then fileData. The data points to the invalid storage area, so the other code to access fileData. When the data will go wrong,

CodePudding user response:

Filep=data=https://bbs.csdn.net/topics/NULL; This sentence to write separately: Filep=NULL; Data=NULL;
  • Related