C 程序在指针运算后崩溃(仅在某些计算机中)
C program crashes after pointer arithmetic (only in some computers)
我有以下代码(不是我写的,简化后只显示有问题的部分):
#include <stdlib.h>
typedef struct test_struct {
unsigned int foo;
char *dummy;
} test_struct;
int main()
{
test_struct *s = (test_struct *) malloc(10 * sizeof(test_struct));
s = (test_struct *)((unsigned long)s + 16);
s->foo = 1; // crash!
}
该程序为 10 个结构分配内存(在我的平台中为 10*24 字节)。然后,指针增加了 16 个字节,并尝试在该位置写入一个数字。
我已经在 4 台计算机上测试了这个片段。其中两个是 运行 on Windows 7 x64,并且运行良好。另一个 运行 在 lubuntu x64 上,也按预期工作。另一个是 Windows 10 x64,它崩溃了。
你能帮我理解这些行有什么问题吗?我正在使用执行此操作的第三方库,但我不知道到底发生了什么。
s = (test_struct *)((unsigned long)s + 16);
在某些平台上 long
不足以存储指针,因此使用 uintptr_t
代替:
s = (test_struct *)((uintptr_t)s + 16);
The program allocates memory for 10 structs (10*24 bytes in my case). Then, the pointer gets an addition of 16 bytes
无论您想实现什么,请注意结构的大小也取决于平台。不仅结构中的字段,而且填充在不同平台上也可能不同。
所以在计算中我们最好使用 sizeof
和 offsetof
而不是像 16
.
这样的幻数
test_struct *s = (test_struct *) malloc(10 * sizeof(test_struct)); s = (test_struct *)((unsigned long)s + 16);
您的程序中存在多个错误:-
1.you 应该明白内存分配完全取决于 OS 。你如何以及为什么做 16 的增量可能会溢出。
2.After 正在更改存储在 s 中的地址,您正在访问的 foo 现在无效。
3.Using valgrind 并检查是否无效。
我有以下代码(不是我写的,简化后只显示有问题的部分):
#include <stdlib.h>
typedef struct test_struct {
unsigned int foo;
char *dummy;
} test_struct;
int main()
{
test_struct *s = (test_struct *) malloc(10 * sizeof(test_struct));
s = (test_struct *)((unsigned long)s + 16);
s->foo = 1; // crash!
}
该程序为 10 个结构分配内存(在我的平台中为 10*24 字节)。然后,指针增加了 16 个字节,并尝试在该位置写入一个数字。
我已经在 4 台计算机上测试了这个片段。其中两个是 运行 on Windows 7 x64,并且运行良好。另一个 运行 在 lubuntu x64 上,也按预期工作。另一个是 Windows 10 x64,它崩溃了。
你能帮我理解这些行有什么问题吗?我正在使用执行此操作的第三方库,但我不知道到底发生了什么。
s = (test_struct *)((unsigned long)s + 16);
在某些平台上 long
不足以存储指针,因此使用 uintptr_t
代替:
s = (test_struct *)((uintptr_t)s + 16);
The program allocates memory for 10 structs (10*24 bytes in my case). Then, the pointer gets an addition of 16 bytes
无论您想实现什么,请注意结构的大小也取决于平台。不仅结构中的字段,而且填充在不同平台上也可能不同。
所以在计算中我们最好使用 sizeof
和 offsetof
而不是像 16
.
test_struct *s = (test_struct *) malloc(10 * sizeof(test_struct)); s = (test_struct *)((unsigned long)s + 16);
您的程序中存在多个错误:- 1.you 应该明白内存分配完全取决于 OS 。你如何以及为什么做 16 的增量可能会溢出。 2.After 正在更改存储在 s 中的地址,您正在访问的 foo 现在无效。 3.Using valgrind 并检查是否无效。