2

我在这里做一个大学作业,我遇到了一个问题。我正在尝试使用 for 循环将字符串输入存储在结构内的某个点。稍后我打算使用指向数据存储位置的指针来获取字符串。现在的问题是,当我在我的 for 循环中继续前进时,点的地址也发生了变化。这段代码:

printf("B: %p\n", txt->point);
for(i = 0; i < input_sz; i++)
{
    txt->point[i] = input[i];
}
printf("A: %p\n", txt->point);

给出输出:

B: 0x7fc111803200
A: 0x7fc111803265

其中 B 是前值,A 是复制后值。

任何调试此问题的帮助将不胜感激!


编辑:这里有更多代码:

结构:

struct text_storage {
    char* start;
    char* point;
    char* end;
} typedef text_t;

初始化函数:

text_t* text_init(void *memory, size_t size)
{
    text_t* to_return;
    if(size < sizeof(text_t))
    {
        return NULL;
    }
    to_return = (text_t*) memory;
    to_return->start = to_return;

    to_return->end = to_return->start + size;
    to_return->point = to_return->start;

    printf("Start: %p, point: %p, end: %p, end-start: %d\n", to_return->start, to_return->point, to_return->end, (to_return->end - to_return->start));


    return to_return;
}

发生错误的文本存储方法:

int text_store_entry(text_t *txt, const char *input, size_t input_sz)
{
    int to_return;
    char* begin = txt->point;
    int i;

    if(input_sz > (txt->end - txt->point))
    {
        return -1;
    }

    printf("Start: %p, point: %p, end: %p, end-start: %d\n", txt->start, txt->point, txt->end, (txt->end - txt->start));


    printf("B: %p\n", txt->point);
    for(i = 0; i < input_sz; i++)
    {
        txt->point[i] = input[i];
    }
    printf("A: %p\n", txt->point);

}

主要功能(仅用于测试):

int main(int argc, char* argv[])
{
    void* memory = malloc(10000);
    char* a = "hei pa deg din trekkbasun";
    text_t* txt;
    int memoverwritten;

    txt = text_init(memory, 10000);

    memoverwritten = text_store_entry(txt, a, (size_t)26);


    printf("got through\n");
    return 0;
}
4

2 回答 2

3

问题很可能是由于类型结构的初始化造成的struct text_storage。这种结构包含三个指向文本的指针。每个指针都应该被初始化,可能使用malloc. 您的text_init功能无法正确执行此操作。实际上,start存储指针的位置与您要使用的内存的第一个字节重叠。

我猜你需要这样的结构:

typedef struct text_storage {
    char* start;
    char* point;
    char* end;
    char* data;
} text_t;

用这样的函数初始化:

text_t text_init(void *memory, size_t size)
{
  text_t to_return;
  to_return.data = (char *) memory;
  to_return.start = to_return.data;
  to_return.end = to_return.start + size;
  to_return.point = to_return.start;
  return to_return;
}
于 2013-09-21T10:17:11.400 回答
0

Print txt->point in the loop and see the point at which it changes. I'm guessing it changes when assigning to txt->point[0]. I'm not fully familiar with printf, so I'm not sure what it's printing out for you, but the name of an array references the first location. If printf is printing out a pointer, txt->point[i] is always a char pointer, and printf may be dereferencing txt->point, which will get it the first entry, and then showing the address there, which you do assign when you change the point to input[i].

于 2013-09-21T10:34:15.953 回答