我有以下标头文件:
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <assert.h>
#include <stdbool.h>
/** **/
// size: 1B
typedef enum string_proc_func_type_t{
REVERSIBLE = 0,
IRREVERSIBLE = 1
} __attribute__((__packed__)) string_proc_func_type;
// size: 12B
typedef struct string_proc_key_t {
uint32_t length; // 4B
char* value; // 8B (ptr)
} __attribute__((__packed__)) string_proc_key;
typedef void (*string_proc_func) (string_proc_key*);
// size 24B
typedef struct string_proc_list_t {
char* name; // 8B (ptr)
struct string_proc_node_t* first; // 8B (ptr)
struct string_proc_node_t* last; // 8B (ptr)
} __attribute__((__packed__)) string_proc_list;
// size 33B
typedef struct string_proc_node_t {
struct string_proc_node_t* next; // 8B (ptr)
struct string_proc_node_t* previous; // 8B (ptr)
string_proc_func f; // 8B (ptr)
string_proc_func g; // 8B (ptr)
string_proc_func_type type; // 1B
} __attribute__((__packed__)) string_proc_node;
string_proc_list* string_proc_list_create(char* name);
void string_proc_list_destroy(string_proc_list* list);
// Aux functions
uint32_t str_len(char* a);
char* str_copy(char* a);
我已经实现了AUX函数,如下所示:
uint32_t str_len(char* a) {
uint32_t cont = 0;
while(a != NULL && *a != ' ') {
cont++;
a++;
}
return cont;
}
char* str_copy(char* a) {
uint32_t length = str_len(a);
char* copy = malloc(length);
for (uint32_t i = 0; i < length; ++i) {
copy[i] = a[i];
}
return copy;
}
现在,我想在汇编上实现string_proc_list_create
功能,最终以此为此:
; C functions
extern malloc
extern free
extern fopen
extern fclose
extern fprintf
extern str_copy
; structs sizes
%define STRUCT_STRING_PROC_LIST_SIZE 24
; structs offsets
%define STRUCT_STRING_PROC_LIST_NAME_OFFSET 0
%define STRUCT_STRING_PROC_LIST_FIRST_OFFSET 8
%define STRUCT_STRING_PROC_LIST_LAST_OFFSET 16
section .data
section .text
global string_proc_list_create
string_proc_list_create:
push rbp
mov rbp, rsp
push rdi ; save ptr to name
; allocate mem for struct
mov rdi, STRUCT_STRING_PROC_LIST_SIZE
sub rsp, 8 ; align stack
call malloc
add rsp, 8 ; unalign stack
; get ptr to struct at RAX
pop rdi ; get ptr to name en RDI
; save ptr to struct at RBX
push rbx
mov rbx, rax
; copy name
add rsp, 8 ; align stack
call str_copy
add rsp, 8 ; unalign stack
; get ptr to name (copy) at RAX
; initialize struct (ptr to struct at RBX, ptr to name (copy) at RAX)
mov qword [rbx + STRUCT_STRING_PROC_LIST_NAME_OFFSET], rax
mov qword [rbx + STRUCT_STRING_PROC_LIST_FIRST_OFFSET], 0
mov qword [rbx + STRUCT_STRING_PROC_LIST_LAST_OFFSET], 0
pop rbx
pop rbp
ret
然后,我尝试执行此行:
string_proc_list* list = string_proc_list_create("aName");
但是我在ret时会遇到细分故障。我认为我可能会打破堆栈框架,但找不到代码出了问题。有帮助吗?
问题不在您发布的代码中,这是完全正确的(如果您说的是您的意思(,但很可能在使用str_copy
的地方。问题在于,您获得了一个未终止字符串的字符串。你
uint32_t length = str_len(a);
char* copy = malloc(length);
当您必须使用malloc(length+1);
才能允许最终的