I have a dynamic allocated 2d int array, called image, and a format string called format. I then use two nested for loops to get the inputs from standard input, and store them in the 2d array. So I can parse the integers from the inputs with different lengths DYNAMICALLY. For example, if I have a 3x3 2d array, I will need to use inline asm to push the element address in the array 9 times, and a push to the format string. I then call scanf, and balance the stack when finished.
BTW:The width and height of the array is assumed known already.
Here is my code on Windows (X64 system, compiled in x32 code). It works fine.
for (int i = 0; i < height; i++) {
for (int j = width-1; j >=0; j--) {
int tmp_addr = (int)&image[i][j];
__asm push tmp_addr;
}
int pop_size = (width+1) * 4;
__asm {
push format;
call func_scanf;
mov read_size, eax;
add esp, pop_size;
}
}
The code did not work when I port it onto Linux (X64 system, compiled in X64 code).
for (int i = 0; i < height; i++) {
for (int j = width-1; j >=0; j--) {
long tmp_addr = (long)&image[i][j];
//__asm push tmp_addr;
__asm__ __volatile__(
"push %0\n\t"
::"g"(tmp_addr)
);
}
int pop_size = (width+1) * sizeof(long);
/*__asm {
push format;
call func_scanf;
mov read_size, eax;
add esp, pop_size;
}*/
__asm__ __volatile__(
"push %0\n\t"
"call *%1\n\t"
"mov %%rax,%2\n\t"
"add %3,%%rsp"
::"g"(format),"g"(func_scanf),"g"(read_size),"g"(pop_size)
:"%rax","%rsp"
);
}
The error says Segmentation fault when this code is executed. What could go wrong? Thank you!