内存搜索器功能中的无效段错误

时间:2015-08-06 04:02:00

标签: c pointers memory-management segmentation-fault undefined-behavior

我的内存搜索器功能用于定位内存中字符串“initial”的出现。

volatile unsigned char* ptr;
size_t offset_address;
static char nm [8], idx;

for(ptr = ((volatile unsigned char* )&offset_address); idx <= sizeof("initial") - 1; ptr++)
{
    if(*ptr == *("initial" + idx))
        *(nm + idx) = *ptr, idx++;
    else idx = 0;
}

导致“超出授权存储区域的行if(*ptr == *("initial" + idx))访问中的读取错误”有什么问题? (如果我只将指针递增一次,则会出错,但如果我根本不递增指针,则不会发生错误)

1 个答案:

答案 0 :(得分:1)

for循环中可能存在无限循环,然后ptr不断成长。最后,尝试按*ptr推荐它会导致错误。

for(ptr = /*...*/; idx <= sizeof("initial") - 1; ptr++) <-- infinite loop if idx=0
{
    if(*ptr == *("initial" + idx))
        *(nm + idx) = *ptr, idx++;
    else idx = 0; <-- always goes here if no matching
}