I’m trying to write to a file and i get a segmentation fault when i delete the allocated memory. I don’t understant what is the problem, please help:
void writeToLog(string msg) {
int len = msg.size()+1;
char *text = new char(len);
strcpy(text,msg.c_str());
char* p = text;
for(int i=0; i<len; i++){
fputc(*p, _log) ;
p++;
}
delete[] text; //THIS IS WHERE IT CRASHES
}
I also tried without the [ ] but then i get
*** glibc detected *** ./s: free(): invalid next size (fast): 0x09ef7308 ***
So what is the problem?
Thanks!
Well,
delete[]doesn’t balancenew char(N), it balancesnew char[N]. The former creates a pointer to a singlecharand gives it the valueN; the latter creates a pointer to an array ofcharwith lengthN, and leaves the values indefined.Of course, to write a
std::stringto aFILE *, why not just do:Note that preserves the trailing null character; so does your original code.