sprintf引起的exc_bad_access

时间:2016-09-28 10:21:27

标签: 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++;
}

1 个答案:

答案 0 :(得分:1)

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

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