什么时候在C中未定义指针减法? [英] When is pointer subtraction undefined in C?

查看:137
本文介绍了什么时候在C中未定义指针减法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

char *buf = malloc(bufsize)
char *ptr = buf;
…
while(condition) {
    ptrdiff_t offset = ptr - buf;    // <========== THIS LINE

    // offset will never be negative because we only ever *increase* ptr
    if ((size_t)offset > bufsize) {
        // we need more room
        bufsize += 128;
        buf = realloc(buf, bufsize);
        ptr = buf + offset;  // buf might be in a completely new location
    }
    *ptr++ = …  // write this byte
}

这是有效还是未定义?

我本来以为它是有效的,但是我读到一些关于它未定义的信息,所以我用谷歌搜索了它.这些链接似乎不可避免地声称它是未定义的:

I would have assumed that it's valid, but I read something about it being undefined, so I googled it. These links seem to inescapably claim it's undefined:

  • Secure coding
  • Is subtraction of pointers not pointing to different elements of same array valid in C?

但是,在这些SO问题中没有提及它:

However, no mention of it is made in these SO questions:

  • Pointer subtraction confusion
  • size_t return pointer subtraction
  • Pointer Arithmetic In C

所有这些都谈论不是在同一数组"中的两个指针.这真的意味着堆栈上有一个普通的旧C数组吗?

These all talk about not two pointers being in the same "array". Does that actually mean a plain old C array on the stack?

如果它是未定义的,那对我来说似乎很奇怪……当我访问一个常量指针和一个移动指针时,为什么要强迫我携带一个计数器变量?

If it is undefined, it seems very odd to me… Why force me to carry along a counter variable when I have access to one constant pointer and one moving pointer?

推荐答案

将指向由malloc返回的内存块的指针视为进入同一数组:

Pointers into a block of memory returned by malloc count as being into the same array:

1- 如果分配成功,从[c0>返回的指针[...]可以分配给 指向任何类型的对象的指针,然后使用 在分配的空间中访问此类对象或此类对象的数组(直到该空间) 已被明确释放).

1 - The pointer returned [from malloc] if the allocation succeeds [...] may be assigned to a pointer to any type of object [...] and then used to access such an object or an array of such objects in the space allocated (until the space is explicitly deallocated).

这篇关于什么时候在C中未定义指针减法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆