[英]How to return an assembler value to a C Int Pointer?
我正在編寫一個小的ASM / C程序,用於計算數字的除數。 我得到以下C函數:
#include <stdio.h>
extern void getDivisorCounter(int value, int* result);
int main(int argc, char** argv) {
int number;
printf("Please insert number:\n");
scanf("%d", &number);
int* result;
getDivisorCounter(number, result);
printf("amount of div: %d\n", *result);
return 0;
}
我從以下匯編程序中收到結果:
section .text
global getDivisorCounter
getDivisorCounter:
push ebp
mov ebp, esp
mov ecx, [ebp+8]
mov eax, 0
push ebx
for_loop:
mov ebx, ecx
jmp checking
adding:
add ebx, ecx
checking:
cmp ebx, [ebp+8]
jg looping
jl adding
inc eax
looping:
loop for_loop
mov [ebp+12], eax
pop ebx
pop ebp
ret
通過調試,我知道我最終在eax中得到了正確的值。 但是以某種方式,我無法使其由C程序打印。 您能給我一個解決方法的提示嗎?
如有必要,我正在使用NASM和GCC。
您不需要為此的指針。 無論如何,如果您(或分配)堅持要求,則必須1)在C側初始化所述指針,並2)在asm側通過該指針寫入。
例如
int value;
int* result = &value;
和
mov ecx, [ebp+12]
mov [ecx], eax
如果必須使用指針,這並不意味着您需要創建一個額外的指針變量。 您可以只傳遞適當類型的變量的地址。 這將消除丟失內存分配的風險。 缺少內存分配是您出現問題的原因。 result
未指向有效內存。
代替
int val;
int *result = &val; // <<== note the mandatory initialization of your pointer.
getDivisorCounter(number, result);
printf("amount of div: %d\n", val);
您可以使用此:
int result;
getDivisorCounter(number, &result);
printf("amount of div: %d\n", result);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.