Simple loop in NASM from C - c

Im trying to work with nasm from C and just having a hard time with the basics of nasm. Im trying to convert a simple while loop like this
while(j < k)
{k = k + 1;
j = j + 2;
count = count + 1;
}
I know that it will look something like
Loopee:
????
add dword [k], 1
add dword [j], 2
add dword [count], 1
but I'm not sure how to structure the while loop where it only loops until j is no longer less than k.

A while loop is just like an IF statement, except that at the bottom of the body you unconditionally jump back to the IF (the start of the loop).

Related

OpenMP gives (core dumped)

I have loop which I want to parallelize with OpenMP. when I compile with gcc -o prog prog.c -lm -fopenmp I get no errors. But when I execute it, I get segmentation fault(core dumped). The problem surely comes from the OpenMP commands because the program works when I delete the #pragma...
Here is the parallel loop:
ix = (i-1)%ILIGNE+1;
iy = (i-1)/ILIGNE+1;
k = 1;
# pragma omp parallel for private(j,jx,jy,r,R,voisin) shared(NTOT,k,i,ix,iy) num_threads(2) schedule(auto)
for(j = 1;j <= NTOT;j++){
if(j != i){
jx = (j-1)%ILIGNE+1;
jy = (j-1)/ICOLONE+1;
r[k][0] = (jx-ix)*a;
r[k][1] = (jy-iy)*a;
R[k] = sqrt(pow(r[k][0],2.0)+pow(r[k][1],2.0));
voisin[k] = j;
k++;
}
}
I tried to change the stack size to unlimited but it doesn't fix the problem. Please tell me if it is about a memory leak or a race condition or something else? and thank you for your help
As a side note, be careful when you make an array private.
If you allocated it as a static array
e.g.
int R[5] or something similar then that's fine, each thread gets its own personal copy :).
If you malloc these however
e.g.:
int R = malloc(5*sizeof(int));
then it will act as a shared array regardless of whether you define it as private (which could potentially lead to undefined behaviour, segfaults, jibberish in the array etc).
I'm not sure what your code does, but I'm pretty sure the OpenMP version is wrong. Indeed, you parallelised over the j loop, but the heart of your algorithm revolves around the k, which is loosely derived from j and i (which is not presented here BTW).
So when you distribute your j indexes across your OpenMP threads, they all start from a different value of j, but all from the same value of k which is shared. From that, k is incremented quite randomly and the accesses to the various arrays using k are very very likely to generate segmentation faults.
Moreover, arrays r, R and voisin shouldn't be declared private if one want the parallelisation to have any effect.
Finally, C loops like this for(j = 1;j <= NTOT;j++) look utterly suspicious to me for off-by-one accesses... Shouldn't that be rather for(j = 0;j < NTOT;j++)? (just mentioning this since the initial value of k is 1 as well...)
Bottom line is that you'd probably better define k from j's value with k = j<i ? j : j-1 instead of trying to increment it inside the code.
Assuming all the rest is correct, this might be a valid version:
ix = (i-1)%ILIGNE+1;
iy = (i-1)/ILIGNE+1;
# pragma omp parallel for private(j,jx,jy,k) num_threads(2) schedule(auto)
for(j = 1;j <= NTOT;j++){
if(j != i){
k = j<i ? j : j-1;
jx = (j-1)%ILIGNE+1;
jy = (j-1)/ICOLONE+1;
r[k][0] = (jx-ix)*a;
r[k][1] = (jy-iy)*a;
R[k] = sqrt(pow(r[k][0],2.0)+pow(r[k][1],2.0));
voisin[k] = j;
}
}
Still, be careful with the C indexing from 0 to size-1, not from 1 to size...

Simple Loop In Assembly (Branch Unconditionally)

I'm trying to create a simple loop in assembly to perform an instruction until a certain condition is met. For example, I want to implement this C code in assembly:
int compute_sum(int n)
{
i = 2;
sum = 0;
while(i <= n)
{
sum = sum + i;
i = i + 4;
}
}
The outline I made for myself is this:
/ ADD (compute sum)
/ Increment to keep track of # times passed through loop
/ SNA (skip if difference between user input and number is < 0)
/ BUN xxx (repeat)
I read in user input and have the decimal representation, but do not know the address that should follow BUN so that the instructions are repeated. These are all done in simple computer instructions
You might want to practice getting into the correct mindset by using C without structured conditions (ie using labels and gotos):
i = 2;
sum = 0;
loop:
if (i > n) goto finished;
sum = sum + i;
i = i + 4;
goto loop;
finished:
This is perfectly valid C (albeit archaic) but shows what you need to do at the simplest level. Compare i with n and branch to finished if greater and branch unconditionally to the loop level.
If the assembler language you are using does not have an unconditional branch then you can set the flag and branch (eg SEC, BCS loop) or count on the idea that i will not overflow and when you add 4, branch on no overflow - just make sure it doesn't fail catastrophically if this is not the case.
So, in assembler (which shares the label syntax), you would have:
loop:
cmp i, n ; Or register equivelents
bgt finished
....
add i, 4
bvc loop
finished:

Using Nested For Loops and an Array in MIPS

This is a homework assignment, I've written the whole program myself, run through it in the debugger, and everything plays out the way I mean it to EXCEPT for this line:
sw $t1, counter($a3)
The assignment is to convert this snippet of C code to MIPS
for(i = 0; i < a; i++) {
for(j = 0; j < b; j++) {
C[2 * i] = i – j; } }
All the registers change values the way they should in my program except for $a3 - It never changes.
Changes: An array needed to be declared and "pointed to" by a register and a label can't be used for an offset in the manner I started with
EDIT: Here's the finished, working code
Recap answer from the comments
Your $a3 register, is supposed to be loaded with the address of an array defined in the .data section.
One big problem with your code is how you constructed your loops. The best way is to translate your loops step by step, and one loop at a time. Also, remember that :
for( i = 0; i < a; i++ )
{
loop_content;
}
Is equivalent to :
i = 0;
while( i < a )
{
loop_content;
i++;
}
Which is easier to translate in assembly. The condition just have to be negated, has you need an "exit" condition, and not a "continue" condition as in a while loop. Your code will be much clearer and easier to understand (and less error prone).
Your "out of range" error comes from here : sw $t1, counter($a3). Here counter is a label, and therefore an address. Thus counter($a3) is doing "$a3 (=0x10010008) + address of counter (=0x100100f8)", giving 0x20020100, which is clearly not what you want (and non-sense).
Oh, and in the sw $r, offset($a) MIPS instruction, offset MUST be a 16-bit CONSTANT. Here, you use a 32-bit address, but it's just that the assembler kindly translate sw $t1, counter($a3) to $x = $a3 + counter; sw $t1, 0($x), which is why you may see a sw with 0 as offset.

How to loop for a fixed number of iterations?

Is there any way of making a for loop iterate a fixed number of times, even though the right side of the interval might be increasing ?
I want to do this without declaring an additional variable to use as a copy of the initial inc.
For example:
for (i = 0; i < inc; i++)
{
if (condition)
{
inc++;
}
}
I am pretty sure that if inc increases, the for will execute more than inc - 1 times. How can I iterate exactly inc times, without using a copy of inc ?
for (i = inc; i > 0; i--) {
if (condition) {
inc++;
}
}
This would work since you only assign inc once.
I think you are possibly looking for a 'range', you don't say what language its for but in python something like:
inc = 2
for i in range[0:10]:
if i > inc:
inc=inc+1
print inc

For vs. while in C programming?

There are three loops in C: for, while, and do-while. What's the difference between them?
For example, it seems nearly all while statements can be replaced by for statements, right? Then, what's the advantage using while?
A while loop will always evaluate the condition first.
while (condition) {
//gets executed after condition is checked
}
A do/while loop will always execute
the code in the do{} block first
and then evaluate the condition.
do {
//gets executed at least once
} while (condition);
A for loop allows you to initiate a counter variable, a check condition, and a way to increment your counter all in one line.
for (int x = 0; x < 100; x++) {
//executed until x >= 100
}
At the end of the day, they are all still loops, but they offer some flexibility as to how they are executed.
Here is a great explanation of the reasoning behind the use of each different type of loop that may help clear things up. Thanks clyfe
The main difference between the for's
and the while's is a matter of
pragmatics: we usually use for when
there is a known number of iterations,
and use while constructs when the
number of iterations in not known in
advance. The while vs do ... while
issue is also of pragmatics, the
second executes the instructions once
at start, and afterwards it behaves
just like the simple while.
For loops are especially nice because they are concise. In order for this for loop:
for (int x = 0; x < 100; x++) {
//executed until x >= 100
}
to be written as a while loop, you'd have to do the following:
int count = 0;
while (count < 100) {
//do stuff
count++;
}
In this case, there's just more stuff to keep up with and the count++; could get lost in the logic. This could end up being troublesome depending on where count gets incremented, and whether or not it should get incremented before or after the loop's logic. With a for loop, your counter variable is always incremented before the next iteration of the loop, which adds some uniformity to your code.
For the sake of completeness, it's probably meaningful to talk about break and continue statements here which come in handy when doing loop processing.
break will instantly terminate the current loop and no more iterations will be executed.
//will only run "do stuff" twice
for (int x = 0; x < 100; x++) {
if (x == 2) {
break;
}
//do stuff
}
continue will terminate the current iteration and move on to the next one.
//will run "do stuff" until x >= 100 except for when x = 2
for (int x = 0; x < 100; x++) {
if (x == 2) {
continue;
}
//do stuff
}
Note that in a for loop, continue evaluates the part3 expression of for (part1; part2; part3); in contrast, in a while loop, it just jumps to re-evaluate the loop condition.
If there is a strong concern about speed and performance, the best approach is to verify the code produced by the compiler at the assembly level.
For instance, the following code shows that the "do-while" is a bit faster. This because the "jmp" instruction is not used by the "do-while" loop.
BTW, in this specific example, the worst case is given by the "for" loop. :))
int main(int argc, char* argv[])
{
int i;
char x[100];
// "FOR" LOOP:
for (i=0; i<100; i++ )
{
x[i] = 0;
}
// "WHILE" LOOP:
i = 0;
while (i<100 )
{
x[i++] = 0;
}
// "DO-WHILE" LOOP:
i = 0;
do
{
x[i++] = 0;
}
while (i<100);
return 0;
}
// "FOR" LOOP:
010013C8 mov dword ptr [ebp-0Ch],0
010013CF jmp wmain+3Ah (10013DAh)
for (i=0; i<100; i++ )
{
x[i] = 0;
010013D1 mov eax,dword ptr [ebp-0Ch] <<< UPDATE i
010013D4 add eax,1
010013D7 mov dword ptr [ebp-0Ch],eax
010013DA cmp dword ptr [ebp-0Ch],64h <<< TEST
010013DE jge wmain+4Ah (10013EAh) <<< COND JUMP
010013E0 mov eax,dword ptr [ebp-0Ch] <<< DO THE JOB..
010013E3 mov byte ptr [ebp+eax-78h],0
010013E8 jmp wmain+31h (10013D1h) <<< UNCOND JUMP
}
// "WHILE" LOOP:
i = 0;
010013EA mov dword ptr [ebp-0Ch],0
while (i<100 )
{
x[i++] = 0;
010013F1 cmp dword ptr [ebp-0Ch],64h <<< TEST
010013F5 jge wmain+6Ah (100140Ah) <<< COND JUMP
010013F7 mov eax,dword ptr [ebp-0Ch] <<< DO THE JOB..
010013FA mov byte ptr [ebp+eax-78h],0
010013FF mov ecx,dword ptr [ebp-0Ch] <<< UPDATE i
01001402 add ecx,1
01001405 mov dword ptr [ebp-0Ch],ecx
01001408 jmp wmain+51h (10013F1h) <<< UNCOND JUMP
}
// "DO-WHILE" LOOP:
i = 0;
. 0100140A mov dword ptr [ebp-0Ch],0
do
{
x[i++] = 0;
01001411 mov eax,dword ptr [ebp-0Ch] <<< DO THE JOB..
01001414 mov byte ptr [ebp+eax-78h],0
01001419 mov ecx,dword ptr [ebp-0Ch] <<< UPDATE i
0100141C add ecx,1
0100141F mov dword ptr [ebp-0Ch],ecx
01001422 cmp dword ptr [ebp-0Ch],64h <<< TEST
01001426 jl wmain+71h (1001411h) <<< COND JUMP
}
while (i<100);
For the sake of readability
They're all interchangeable; you could pick one type and use nothing but that forever, but usually one is more convenient for a given task. It's like saying "why have switch, you can just use a bunch of if statements" -- true, but if it's a common pattern to check a variable for a set of values, it's convenient and much easier to read if there's a language feature to do that
If you want a loop to execute while a condition is true, and not for a certain number of iterations, it is much easier for someone else to understand:
while (cond_true)
than something like this:
for (; cond_true ; )
Remember, a for loop is essentially a fancy while loop. They're the same thing.
while <some condition is true> {
// do some stuff
// possibly do something to change the condition
}
for ( some var, <some condition is true>; increment var ) {
}
The advantage of a for loop is that it's harder to accidentally do an infinite loop. Or rather, it's more obvious when you do one because you generally put the loop var in the initial statement.
A while loop is more clear when you're not doing a standard incrementing pattern. For example:
int x = 1;
while( x != 10 ) {
if ( some condition )
x = 10;
else
x += 5;
}
You should use such a loop, that most fully conforms to your needs.
For example:
for(int i = 0; i < 10; i++)
{
print(i);
}
//or
int i = 0;
while(i < 10)
{
print(i);
i++;
}
Obviously, in such situation, "for" looks better, than "while".
And "do while" shoud be used when some operations must be done already before the moment when condition of your loop will be checked.
Sorry for my bad english).
One common misunderstanding withwhile/for loops I've seen is that their efficiency differs. While loops and for loops are equally efficient. I remember my computer teacher from highschool told me that for loops are more efficient for iteration when you have to increment a number. That is not the case.
For loops are simply syntactically sugared while loops, and make iteration code faster to write.
When the compiler takes your code and compiles it, it is translating it into a form that is easier for the computer to understand and execute on a lower level (assembly). During this translation, the subtle differences between the while and for syntaxes are lost, and they become exactly the same.
A for suggest a fixed iteration using an index or variants on this scheme.
A while and do... while are constructions you use when there is a condition that must be checked each time (apart from some index-alike construction, see above). They differ in when the first execution of the condition check is performed.
You can use either construct, but they have their advantages and disadvantages depending on your use case.
I noticed some time ago that a For loop typically generates several more machine instructions than a while loop. However, if you look closely at the examples, which mirror my observations, the difference is two or three machine instructions, hardly worth much consideration.
Note, too, that the initializer for a WHILE loop can be eliminated by baking it into the code, e. g.:
static int intStartWith = 100;
The static modifier bakes the initial value into the code, saving (drum roll) one MOV instruction. Of greater significance, marking a variable as static moves it outside the stack frame. Variable alignment permitting, it may also produce slightly smaller code, too, since the MOV instruction and its operands take more room than, for example an integer, Boolean, or character value (either ANSI or Unicode).
However, if variables are aligned on 8 byte boundaries, a common default setting, an int, bool, or TCHAR baked into code costs the same number of bytes as a MOV instruction.
They are all the same in the work they do. You can do the same things using any of them. But for readability, usability, convenience etc., they differ.
A difference between while and do-while is that while checks the loop condition and if this is true, the body is executed and the condition checked again. The do-while checks the condition after execution of the body, so with do-while the body is executed at least one time.
Of course you can write a while loop as a do-while and vv, but this usually requires some code duplication.
One peculiarity of the do while is that you need a semi-colon after the while to complete. It is often used in macro definitions to execute several statements only once while constraining the impact of the macro. If macros where defined as blocks, some parsing errors may occur.
One explanation among others
For loops (at least considering C99) are superior to while loops because they limit the scope of the incremented variable(s).
Do while loops are useful when the condition is dependant on some inputs. They are the most seldom used of the three loop types.
Between for and while: while does not need initialization nor update statement, so it may look better, more elegant; for can have statements missing, one two or all, so it is the most flexible and obvious if you need initialization, looping condition and "update" before looping. If you need only loop condition (tested at the beginning of the loop) then while is more elegant.
Between for/while and do-while: in do-while the condition is evaluated at the end of the loop. More confortable if the loop must be executed at least once.
WHILE is more flexible. FOR is more concise in those instances in which it applies.
FOR is great for loops which have a counter of some kind, like
for (int n=0; n<max; ++n)
You can accomplish the same thing with a WHILE, of course, as others have pointed out, but now the initialization, test, and increment are broken across three lines. Possibly three widely-separated lines if the body of the loop is large. This makes it harder for the reader to see what you're doing. After all, while "++n" is a very common third piece of the FOR, it's certainly not the only possibility. I've written many loops where I write "n+=increment" or some more complex expression.
FOR can also work nicely with things other than a counter, of course. Like
for (int n=getFirstElementFromList(); listHasMoreElements(); n=getNextElementFromList())
Etc.
But FOR breaks down when the "next time through the loop" logic gets more complicated. Consider:
initializeList();
while (listHasMoreElements())
{
n=getCurrentElement();
int status=processElement(n);
if (status>0)
{
skipElements(status);
advanceElementPointer();
}
else
{
n=-status;
findElement(n);
}
}
That is, if the process of advancing may be different depending on conditions encountered while processing, a FOR statement is impractical. Yes, sometimes you could make it work with a complicated enough expressions, use of the ternary ?: operator, etc, but that usually makes the code less readable rather than more readable.
In practice, most of my loops are either stepping through an array or structure of some kind, in which case I use a FOR loop; or are reading a file or a result set from a database, in which case I use a WHILE loop ("while (!eof())" or something of that sort).
They are pretty much same except for do-while loop. The for loop is good when you have a counter kind of variable. It makes it obvious. while loop makes sense in cases where a flag is being checked as show below :
while (!done) {
if (some condtion)
done = true;
}
while and for statements can both be used for looping in programming. It will depend on the programmer as to whether the while loop or for loop is used. Some are comfortable using while loop and some are with for loop.
Use any loop you like. However, the do...while loop can be somewhat tricky in C programming.
/*
while loop
5 bucks
1 chocolate = 1 bucks
while my money is greater than 1 bucks
select chocolate
pay 1 bucks to the shopkeeper
money = money - 1
end
come to home and cant go to while shop because my money = 0 bucks
*/
#include<stdio.h>
int main(){
int money = 5;
while( money >= 1){
printf("inside the shopk and selecting chocolate\n");
printf("after selecting chocolate paying 1 bucks\n");
money = money - 1 ;
printf("my remaining moeny = %d\n", money);
printf("\n\n");
}
printf("dont have money cant go inside the shop, money = %d", money);
return 0;
}
infinite money
while( codition ){ // condition will always true ....infinite loop
statement(s)
}
please visit this video for better understanding
https://www.youtube.com/watch?v=eqDv2wxDMJ8&t=25s
/*
for loop
5 bucks
for my money is greater than equal to 1 bucks 0 money >= 1
select chocolate
pay 1 bucks to the shopkeeper
money = money - 1 1-1 => 0
end
*/
#include<stdio.h>
int main(){
int money = 5;
for( ; money >= 1; ){ 0>=1 false
printf("select chocolate \n");
printf("paying 1 bucks to the shopkeeper\n");
money = money - 1; 1-1 = 0
printf(" remaining money =%d\n", money);
printf("\n\n");
}
return 0;
}
For better understanding please visit https://www.youtube.com/watch?v=_vdvyzzp-R4&t=25s

Resources