在一个线程中,我正在使用 fgets() 从文件中读取输入。fgets() 给了我 buf,当我标记化时,返回的 char 指针表示地址超出范围
char buf[1024];
char data[1024];//for use of strtok
char* dptr = NULL;
memset(&data,0,sizeof(data));
memset(&buf,0,sizeof(buf));
if(NULL != fgets(buf,1024,fp))
{
/*remove new line char from fgets input*/
if(buf[strlen(buf)-1] == '\n')
{
buf[strlen(buf)-1] = '\0';
}
/*making a local copy of buffer for strtok use*/
strncpy(data,buf,1024);
/*Get value 1 */
dptr = NULL;
char* rs;
dptr = strtok_r(data," ", &rs);
if(dptr == NULL)
{
fprintf(stderr,"incorrect file format\n");
return -1;
}
/*dptr is not NULL but cannot access it even in gdb*/
int temp = atoi(dptr);//accessing dptr here gives address out of bound error.
我认为使用指针 dptr 访问数据缓冲区存在一些问题。虽然无法分析。我尝试使用 sscanf 和数组元素替换进行标记和访问,这很有效-
dptr = buf;
int i=0;
while(*dptr != '\n' || *dptr != '\0' && i<1024)
{
if(*dptr == '\t')
{
buf[i] = '\0';
}
dptr++;
i++;
}
char v1[256],v2[256],v3[256];
sscanf(buf,"%s %s %s",v1,v2,v3);