Rajat Verma
Rajat Verma

Reputation: 2590

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();
}

Upvotes: 2

Views: 82

Answers (2)

Gopi
Gopi

Reputation: 19864

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

Upvotes: 1

Vagish
Vagish

Reputation: 2547

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.

Upvotes: 2

Related Questions