C++ C++;指针数组和缓冲
我在读取文件时遇到问题。 在跟踪发现C++ C++;指针数组和缓冲,c++,C++,我在读取文件时遇到问题。 在跟踪发现 mybuffmy不会使用(mybuff=new char[1024];)重新初始化,因为调试后,我仍然会在最后看到上一条消息。 当我尝试填充sendbuff时会出现问题,因为相同的问题。 在这一步中会出现一个错误,称为“访问冲突读取位置”(sprintf(sendbuff,mybuff)) 你知道如何解决这个问题吗 char sendbuff[1024]; char * mybuff = new char[]; While(....){ mybuff
mybuff
my不会使用(mybuff=new char[1024];
)重新初始化,因为调试后,我仍然会在最后看到上一条消息。
当我尝试填充sendbuff
时会出现问题,因为相同的问题。
在这一步中会出现一个错误,称为“访问冲突读取位置”(sprintf(sendbuff,mybuff)
)
你知道如何解决这个问题吗
char sendbuff[1024];
char * mybuff = new char[];
While(....){
mybuff = new char [1024];
myfile.read(mybuff ,bufsize);
sprintf(sendbuff,mybuff );
ibytessent=0;
tmpCount = strlen(sendbuff);
ibufferlen = strlen(sendbuff);
ibytessent = send(s,sendbuff,ibufferlen,0);
delete [] mybuff ;
}
我认为您调用ifstream::read()的方式是错误的
read()
不会在末尾添加空字符,您需要检查eofbit
和failbit
引自手册
此函数成功读取和存储的字符数
可通过调用成员gcount访问
我还认为运行时错误是由read()函数的原因造成的,正如上面所述,我也不认为每次迭代都需要重新创建1024字节的空间,为什么不重用缓冲区呢~ 顺便说一句,我尝试重新处理您的问题,我不确定下面的代码是否与您的相同,并且我没有得到任何运行时错误
#include <cstdio>
#include <fstream>
using namespace std;
int bufsize = 1024;
int main(){
char sendbuff[1024];
char * mybuff = new char[];
std::ifstream ifs;
ifs.open ("test.txt", std::ifstream::in);
while(1){
mybuff = new char [1024];
ifs.read(mybuff ,bufsize);
sprintf(sendbuff,mybuff );
int ibytessent=0;
int tmpCount = strlen(sendbuff);
int ibufferlen = strlen(sendbuff);
//ibytessent = send(s,sendbuff,ibufferlen,0);
delete [] mybuff ;
}
return 0;
}
#包括
#包括
使用名称空间std;
int bufsize=1024;
int main(){
char sendbuff[1024];
char*mybuff=新字符[];
std::ifstream-ifs;
ifs.open(“test.txt”,std::ifstream::in);
而(1){
mybuff=新字符[1024];
如果读取(mybuff,bufsize);
sprintf(sendbuff,mybuff);
int ibytessent=0;
int tmpCount=strlen(sendbuff);
int ibufferlen=strlen(sendbuff);
//ibytessent=send(s,sendbuff,ibufferlen,0);
删除[]mybuff;
}
返回0;
}
Sorry忘记添加删除部分Sorry读取时没有发生错误,但似乎是在指针数组的开头追加错误,导致“访问冲突读取位置”的错误在此步骤发生(sprintf(sendbuff,mybuff))。错误发生的位置不同,以及在哪里展出。如果read()
没有添加空字符,那么sprintf()
将读取缓冲区的末尾,如果缓冲区中碰巧没有空字符。这就是您将看到错误影响的地方,但实际的错误发生在您未能向数据末尾添加空字符之前。如果假设实际错误总是在问题报告的行上,那么调试就会困难得多。