strcpy错误的原因是什么
当我尝试执行该程序时,出现分段错误。可能是什么原因?
#include<stdio.h>
#include<malloc.h>
#include<string.h>
#define UWT unsigned int
#define DIR_LEN 1024
typedef struct fileParsedData{
UWT weight;
char *dir;
}FILEPARSEDATA;
int parseData(char *fileData,FILEPARSEDATA *fPD){
char tmpStr[DIR_LEN] = {0};
strcpy(tmpStr,strchr(fileData,' ') + 1);
*(strchr(tmpStr,'\n')) = '\0';
fPD->weight = atoi(fileData);
if((fPD->dir = (char *)malloc(strlen(tmpStr) + 1)) != NULL ){
memset(&fPD->dir,0,strlen(tmpStr)+1);
strcpy(fPD->dir,tmpStr);
return 0;
}
return -1;
}
int main(){
char fileData[10] = " hai\n";
FILEPARSEDATA fPD;
memset(&fPD,0,sizeof(FILEPARSEDATA));
parseData(fileData,&fPD);
return 0;
}
When I try to execute this program I am getting segmentation fault. What could be the reason?
#include<stdio.h>
#include<malloc.h>
#include<string.h>
#define UWT unsigned int
#define DIR_LEN 1024
typedef struct fileParsedData{
UWT weight;
char *dir;
}FILEPARSEDATA;
int parseData(char *fileData,FILEPARSEDATA *fPD){
char tmpStr[DIR_LEN] = {0};
strcpy(tmpStr,strchr(fileData,' ') + 1);
*(strchr(tmpStr,'\n')) = '\0';
fPD->weight = atoi(fileData);
if((fPD->dir = (char *)malloc(strlen(tmpStr) + 1)) != NULL ){
memset(&fPD->dir,0,strlen(tmpStr)+1);
strcpy(fPD->dir,tmpStr);
return 0;
}
return -1;
}
int main(){
char fileData[10] = " hai\n";
FILEPARSEDATA fPD;
memset(&fPD,0,sizeof(FILEPARSEDATA));
parseData(fileData,&fPD);
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题就在这里:
上面的行应该是这样的:
否则,您不仅将
fPD->dir
pointer 归零,而且还会立即损坏内存它。将指针清零后,后续的 strcpy() 就会进入指向的内存段错误。事实上,整个
memset()
行显得多余,因为它后面紧跟着strcpy()
。The problem is here:
The above line should read:
Otherwise, you're not only zeroing out the
fPD->dir
pointer, you're also corrupting memory immediately after it. Once you've zeroed out the pointer, the subsequentstrcpy()
into the pointed-to memory segfaults.In fact, that entire
memset()
line appears redundant since it's followed immediately by thestrcpy()
.