gpt4 book ai didi

c++ - sprintf 引起的 exc_bad_access

转载 作者:行者123 更新时间:2023-11-30 20:22:21 24 4
gpt4 key购买 nike

执行以下代码时,我在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com