简体   繁体   English

为什么此C代码进入循环?

[英]Why This C Code Goes into Loop?

#include <stdio.h>
#include <stdint.h>
int p()
{
    char data[7]="Hello!\0";
    uint64_t *ptr=((uint64_t)data + 0x18);
    printf("%s",data);
    (*ptr)-=10;
    return 0x00;
}

int main(int argc,char **argv)
{
    p();
}

As mentioned in other answers and in comments writing char data[7]="Hello!\\0"; 如其他答案和注释中所述,编写char data[7]="Hello!\\0"; could be a problem but I dont think that is the only source of problem here. 可能是一个问题,但我认为这不是问题的唯一来源。

My guess is : uint64_t *ptr=((uint64_t)data + 0x18); 我的猜测是: uint64_t *ptr=((uint64_t)data + 0x18);

(*ptr)-=10; By doing this probably you are modifying return address from stack or doing something like that. 通过这样做,您可能正在修改堆栈中的返回地址或执行类似的操作。

What you have is undefined behavior. 您所拥有的是未定义的行为。

char data[7]="Hello!\0";

Writing to the array out of bound leads to undefined behavior.This is not the right way to null terminate a string.You can opt for one of the below options. 越界写入数组会导致不确定的行为,这不是将字符串终止为null的正确方法,您可以选择以下选项之一。

Change it to 更改为

char data[7]="Hello!";

You can even have 你甚至可以拥有

char data[]="Hello!";

Edits: 编辑:

By doing this 通过做这个

uint64_t *ptr=((uint64_t)data + 0x18);

You are making your pointer point to some memory location which is not allocated by you.Later you try to write to this location 您正在将指针指向您未分配的某个内存位置。稍后尝试写入此位置

(*ptr)-=10;

So accessing array out of bound or writing to some memory which is not allocated by you leads to undefined behavior.You need to fix them first 因此,超出范围访问数组或写入一些您未分配的内存会导致未定义的行为。您需要首先修复它们

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM