【问题标题】:MIPS (MARS Simulator) - How to Store Compile-Time String Literals in the HeapMIPS (MARS Simulator) - 如何在堆中存储编译时字符串文字
【发布时间】:2020-02-03 17:33:46
【问题描述】:

在了解了 MARS 中的 .macros 后,我决定制作一些以使我的源代码更具可读性。
这种宏的一个例子是我的 string length 宏:

#Gets the length of a string from an address
#Result is in the second operand
#Doesn't count any null-terminators or newlines at the end of the input
#Call example:  strlen MyString,$s0
.macro strlen(%str, %i)
    la $t0,%str
    __strlen_loop:
        lb $t1,0($t0)
        #Exit the loop if this byte is null ('\0') or a newline ('\n')
        beqz $t1,__strlen_end
        beq $t1,'\n',__strlen_end
        inc $t0               #Increment-by-one macro
        j __strlen_loop
    __strlen_end:
    la $t1,%str
    sub %i,$t0,$t1
.end_macro

此宏有效,但它依赖于预定义的地址才能工作 (%str)。
为了尝试解决这个问题,我为 value 字符串宏创建了以下 string length:

#Gets the string length of a value string (stores the string in .data)
#Call example:  strlen_v "Hello World!",$s0
.macro strlen_v(%str,%i)
    #Create a label for the string
    .data
    __strlen_v_label: .asciiz %str
    .text
    #Get the length
    strlen __strlen_v_label,%i
.end_macro

不幸的是,还有另一个问题。第二个宏将值字符串存储在.data 中,它只有0x30000 字的空间(地址0x10010000 到地址0x10040000)。
最好将值字符串存储在 上,因为它有更多空间并且我将能够更有效地管理内存。


是否可以使用.data在堆上存储编译时值字符串?我发现的唯一示例是用户输入字符串和已存储在.data 中的字符串,这两者都不适用于此问题。

【问题讨论】:

    标签: string macros mips


    【解决方案1】:

    是否可以在不使用 .data 的情况下将编译时值字符串存储在堆上?

    不是真的。根据定义,在程序启动时堆在概念上是空的。而且,根据定义,字符串文字是在数据部分中初始化的常量。只能在运行时分配堆空间,不能在编译时分配;因此,在运行时,您可以分配堆空间并将字符串从文字数据移动到堆中......


    但是,请注意 MARS 和 QtSPIM 允许为 .data 提供参数,这是放置后续内容的位置。例如,我们可以做.data 0x10040000,这将导致后续的字符串文字被放置在那里,例如。但是,这会干扰正常的堆操作,因为您的第一个 sbrk 系统调用仍将返回 0x10040000,即使用 .data 0x10040000 放置在那里的字符串文字占用的内存,因为 sbrk 系统调用不知道该指令。


    从长远来看,将字符串长度定义为函数而不是宏可能会更符合您的需求:

    • 您可以确定字符串文字、本地字符串或基于堆的字符串的长度,
    • 您的注册约定将属于正常的调用约定(甚至不确定是否存在宏的注册约定),
    • 您会将字符串文字声明的关注点与字符串长度操作分开。

    【讨论】:

      猜你喜欢
      • 2021-06-11
      • 1970-01-01
      • 2018-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多