Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error while modifying mallocated string in a C struct with asm function

i would like to modify a string inside a C structure with an asm function but it is not working properly…

Let say that i have this type of structure on a 64 bits architecture :

typedef struct my_struct
{
    char letter1;
    char letter2;
    char *string;
}my_struct;

Because of the structure padding, sizeof(my_struct) should be 16 because :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

typedef struct my_struct
{
    char letter1; // 1 byte
    char letter2; // 1 byte
    //6 bytes of padding
    char *string; // 8 bytes
}my_struct;

so, if i call this asm function :

void string_change(my_struct *s);

i could change for example the first letter of the struct string with :

mov byte [rdi+8],'x'

but it is not working… could you help me ?
Thanks a lot.

Here is my C code :

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct my_struct
{
    char letter1;
    char letter2;
    char *string;
}my_struct;

void string_change(my_struct *s);

int main(void)
{
    my_struct s;
    s.string = malloc(sizeof(char)*8);
    strcpy(s.string,"bonjour");
    printf("before call : s.string = %s\n",s.string);
    string_change(&s);
    printf("after call : s.string = %s\n",s.string);
    free(s.string);
    return 0;
}

and here is my assembly code :

bits 64
global string_change
section .text

string_change:
    mov byte [rdi+8],'x';
    ret

>Solution :

To follow up on Peter Cordes comment:

string_change:                         ;rdi = ptr to structure
        mov     rdi,[rdi+8]            ;rdi = ptr to string
        mov     byte [rdi],'x'         ;change first character of string
        ret
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading