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
}
这是有效还是未定义?
我本以为它是有效的,但我读到一些关于它未定义的信息,所以我用谷歌搜索了它。这些链接似乎不可避免地声称它是未定义的:
- Secure coding
- Is subtraction of pointers not pointing to different elements of same array valid in C?
但是,这些 SO 问题中没有提及它:
这些都在谈论没有两个指针在同一个“数组”中。这是否真的意味着堆栈上有一个普通的旧 C 数组?
如果它是未定义的,我觉得很奇怪……当我可以访问一个常量指针和一个移动指针时,为什么要强制我携带一个计数器变量?
最佳答案
指向由 malloc
返回的内存块的指针算作在同一个数组中:
7.22.3 Memory management functions
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 - 什么时候在 C 中未定义指针减法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12099719/