[英]How to return an assembler value to a C Int Pointer?
I am writing a small ASM/C-Program for calculating the number of dividers of a number. 我正在编写一个小的ASM / C程序,用于计算数字的除数。 I got the following C function:
我得到以下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;
}
where I receive a result from the following assembler programm: 我从以下汇编程序中收到结果:
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
From Debugging, I know, that I end up with the right value in eax. 通过调试,我知道我最终在eax中得到了正确的值。 But somehow I cannot get it to be printed by my C programm.
但是以某种方式,我无法使其由C程序打印。 Could you give me a hint on how to solve this?
您能给我一个解决方法的提示吗?
If neccessary, I am using NASM and GCC. 如有必要,我正在使用NASM和GCC。
You do not need a pointer for this. 您不需要为此的指针。 Anyway, if you (or the assignment) insist, you must 1) initialize said pointer on the C side and 2) write through that pointer on the asm side.
无论如何,如果您(或分配)坚持要求,则必须1)在C侧初始化所述指针,并2)在asm侧通过该指针写入。
Eg 例如
int value;
int* result = &value;
and 和
mov ecx, [ebp+12]
mov [ecx], eax
If you must use a pointer, this does not mean you need to create an extra pointer variable. 如果必须使用指针,这并不意味着您需要创建一个额外的指针变量。 You can just pass the address of a variable of proper type.
您可以只传递适当类型的变量的地址。 This would eliminate the risk of missing memory allocation.
这将消除丢失内存分配的风险。 Missing memory allocation is the reason for your problem.
缺少内存分配是您出现问题的原因。
result
does not point to valid memory. result
未指向有效内存。
Instead of 代替
int val;
int *result = &val; // <<== note the mandatory initialization of your pointer.
getDivisorCounter(number, result);
printf("amount of div: %d\n", val);
you could use this: 您可以使用此:
int result;
getDivisorCounter(number, &result);
printf("amount of div: %d\n", result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.