0

我知道如果你想说两个字符输入,你会使用:

input_str:  .ascii "??"  

然后:

mov $2, %edx

比如在:

.data               
input_str:  .ascii "??" 

.text               
.global _start          
_start:             
    mov $3, %eax          # eax = 3 = function number for "read"
    mov $0, %ebx          # ebx = 0 = file descriptor (stdin)
    mov $input_str, %ecx  # ecx = address of input buffer
    mov $2, %edx          # edx = buffer maximum size
    int $0x80             # Call Linux kernel API
                          # eax = error code or number of bytes read

ETC...

但是,如果你要求一个随机长度的句子呢?输入后如何读取有多少?

4

1 回答 1

1

处理随机长度数据有不同的技巧,所有这些技巧都需要动态分配的内存。

在 Linux 中提供它的最简单方法是使用sys_brk函数,但它只允许分配一个内存块。

有提供堆管理的库。FreshLib就是这样一个完全用汇编语言编写的库。另一种选择是与 C 标准库链接。

那么,有两种情况要读取动态分配的缓冲区中的数据,这取决于您是否提前(在运行时)知道数据长度。

已知数据大小

这很简单 - 分配所需大小的缓冲区并完全读取数据。

未知数据大小 - 所谓的流数据

阅读然后复制

在内存中读取流数据的唯一可能方法是读取该数据的固定块,然后将其复制到动态分配的缓冲区中。当缓冲区被填满时,您需要以更大的大小重新分配它,然后继续直到读取所有数据。

Note, that the memory reallocation is expensive operation, so it is better to allocate more than needed memory. Common algorithm is to double the size of the allocated memory on every reallocation. Personally I think this strategy is too aggressive and often use multiplying the size by 1.5;

Don't read the whole data at all

It is often possible to not read the whole data in the memory, but to process it on the fly as it is read in small fixed chunks. This method needs a little bit more complex algorithms, but has the big advantage to use very small memory, not need dynamically allocated memory and avoids the copy of the data between multiply memory locations.

于 2013-03-15T05:57:24.713 回答