[英]segmentation fault due to strcpy()
why am i getting segmentation fault in strcpy()? 为什么我在strcpy()中遇到分段错误?
the program gets compiled without any problem but i am getting a segmentation fault because of strcpy please suggest me a way out. 该程序被编译没有任何问题,但由于strcpy我遇到了分段错误,请为我提供解决方法。
struct obj
{
char objcode[100];
}o[10];
int main()
{
char buffer[500],statement[50][50];/*storing each statement*/
int i=0,fd;
int j=0,k=0;
char *tok;
fd=open("objectprogram.txt",O_RDONLY);
const ssize_t r=read(fd,buffer,500);
buffer[r]='\0';
char *sta;
sta=strtok(buffer,"\n");
while(sta!=NULL)
{
strcpy(statement[i],sta);
i++;
sta=strtok(NULL,"\n");
}
for(j=1;j<i-1;j++)
{
tok=strtok(statement[j],"^");
tok=strtok(NULL,"^");
tok=strtok(NULL,"^");
while(tok!=NULL)
{
tok=strtok(NULL,"^");
strcpy(o[k].objcode,tok);
}
}
}
Your check for tok==NULL
in the while
loop happens after the call to strcpy
, not before. while
循环中对tok==NULL
检查发生在对strcpy
的调用之后 ,而不是在调用之后。 You're trying to copy a NULL pointer. 您正在尝试复制NULL指针。
Whenever you get a segmentation fault, the first thing to look for is the possibility of a NULL pointer. 每当遇到分段错误时,首先要寻找的是NULL指针的可能性。
In this code: 在此代码中:
while(tok!=NULL)
{
tok=strtok(NULL,"^");
strcpy(o[k].objcode,tok);
}
You check for tok
's validity before entering the loop but not after it gets changed by strtok()
. 您可以在进入循环之前检查
tok
的有效性,但是在strtok()
更改它之后不进行检查。
A debugger should have been able to identify exactly which line of code had the problem, and from within the debugger you could see if the value of tok
is okay or not at the time strcpy()
gets called. 调试器应该能够准确地识别出哪一行代码有问题,并且从调试器内部您可以看到在
strcpy()
时tok
的值是否正确。
strcpy is not safe in terms of array size, use strncpy instead!! 就数组大小而言,strcpy是不安全的,请改用strncpy !!
ie if you get more data in your input, you will overflow your statement[i]. 即,如果您在输入中获得更多数据,则将溢出语句[i]。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.