简体   繁体   中英

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"; 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);

(*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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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