c++ - sprintf 引起的 exc_bad_access

标签 c++ c exc-bad-access fread fseek

执行以下代码时,我在 xcode 中收到错误 exc_bad_access。

该错误是由以下行引起的:

//Add new line at beginning of hex decode
p += sprintf(p, "%s", "\n");

这可能是因为当创建指针 *p 时它没有指向内存地址吗?如果是这样,知道如何将其指向内存地址吗?

const char *current = "myfile";
FILE *f = fopen(current, "rb");
if (!f)
{
printf(  "Unable to open file! %s", current);
    return;
}
char ch;
int loop = 1;
int sz1,sz2,sz3;

int seeker = offsetof(struct myStruct, contents.datas);

struct myStruct c;

fseek(f,16,SEEK_SET);

//Find specific ID part of struct for printing later
size_t n = fread(&c.ID, sizeof(int), 1, f);

if (n != 1) {
    printf(  "Error Reading File" );
    return;
} else {
    printf("Success reading ID" );
}

int val;
val=fseek(f,0L,SEEK_SET);

if(val!=0)
{
    post( "problem fseeking" );
    return;
}

//find total length of file
fseek(f, 0L, SEEK_END);
sz1 = ftell(f);

//total length minus length from position which seeker is set
fseek(f, seeker, SEEK_SET);
sz2 = sz1 - ftell(f) + 1;

//Determine count for 80 chars and 7 tabs per new line 
int tabs = (sz2 / 80) * 16;// Total size / size of chunk * 8 - 7 tabs and 1 new line char
sz3 = ((sz2 * 2) + tabs + 1 + 16) ;//Total size + nuls + tabs * 2 for 2 bytes

//Create buffer the correct size
char buffer[sz3];
buffer[0] = '\0';

//Create pointer variable to copy to buffer
char *p = buffer;

//Add new line at beginning of hex decode
p += sprintf(p, "%s", "\n");

while (loop < sz2)
{
    if(loop % 40 -
        //Add 7 tabs to the beginning of each new line 1 == 4 ){
        p += sprintf(p, "%s", "\t\t\t\t\t\t\t");
    }
    //Error happening here
    size_t nn = fread(&ch, 1, 1, f);
    if (nn != 1) {
        printf("Errorno: %s", strerror(errno) );
        return;
    } else {
        //printf("Sucess");
    }

    fread(&ch, 1, 1, f);
    if(loop > 4){
        //Convert char to hex
        p += sprintf(p, "%02X", (ch & 0x00FF));
    }

    if(loop % 40 == 4){
        if(loop > 4){
            //Add a new line every 80 chars
            p += sprintf(p, "%s", "\n");
        }
    }
    loop++;
}

最佳答案

首先 *p 由于行而指向程序中的有效内存 char *p = 缓冲区;

但我认为问题在于缓冲区大小,请确保缓冲区大小足以容纳您要放入的字符串。 我确信语句 "p += sprintf(p, "%s", "\t\t\t\t\t\t\t"); "是问题的原因,可能是由于指针 p 指向的缓冲区数组大小不够。

关于c++ - sprintf 引起的 exc_bad_access,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39744713/

相关文章:

objective-c - 将NSDate传递给指针时EXC_BAD_ACCESS

c++ - 使用字符串类型的键存储散列值的最佳结构

c++ - 返回其自身类型的结构的结构属性

转换从 TUN 接口(interface)接收的原始数据包数据

ios - 在加载图 block 之前从 MapView 退出时的 EXC_BAD_ACCESS

iphone - 导入 vcf vcard 文件时的 EXC_BAD_ACESS

c++ - 查找float类型的内存格式

c++ - 如何解释 Variadic 模板中的继承?

使用 strtok_r 创建 C split 函数 - 就像 perl 和 awk

比较 C 中的字符会引发错误