【发布时间】:2018-05-05 15:45:31
【问题描述】:
我使用*ptr 从头到尾迭代一个字符数组(一次一个字节)并设置一些值。当指针指向第一个地址时,算法应该停止。
char *buf = (char*)malloc(sizeof(char) * 3 + 1);
char *ptr = &buf[sizeof buf - 1]; // *ptr point to the last address
*ptr = '\0';
do {
if(alfa) {
*(--ptr) = "teststring"[alfa]; // *ptr decreases value by one
alfa -= i;
} else { *(--ptr) = 'N'; }
} while(*ptr != &buf[0]); // should check if *ptr is now pointing to the start of buf. If that's the case, stop.
但是,在它检查地址是否相等之后,它给了我:
** stack smashing detected **: <unknown> terminated
Aborted (core dumped)
另一个(也许是相关的)事情是:malloc 应该从内存中分配 4 个字节,但是当我检查 sizeof(buf) 时它有 8 个字节(?)。
注意:sizeof(char) * 3 + 1的输出确实是4,但和sizeof(buf)不一样。
【问题讨论】:
-
sizeof buf并没有给你你认为的那样。它返回 pointerbuf的大小,而不是它所指向的大小。顺便说一句,这仍然适用于指针为四个字节的 32 位系统。它不会在指针为 8 个字节的 64 位系统上工作得很好(如您所见)。 -
请不要在 C++ 程序中使用
malloc/free。使用new/delete。甚至更好;使用智能指针(make_unique、make_shared和朋友)和 STL 容器(如std::array和std::vector)。您当前的代码读作“使用 C++ 编译器编译的 C”——您可以做得更好。 -
alfa是如何定义和初始化的? -
@alk alfa 是一个整数
-
...并初始化?