Home > Software engineering >  Error while modifying mallocated string in a C struct with asm function
Error while modifying mallocated string in a C struct with asm function

Time:03-21

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 :

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

CodePudding user response:

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
  • Related