How to step through a C program in Anjuta? - c

I need to step through this program, but the icons related to debugging are greyed out, even if I set the configuration to 'debug'. Any idea how this is supposed to work?
#include <stdio.h>
int main( void )
{
int number = 7;
printf ( "%d", number % 2 );
number = number / 2;
printf ( "%d", number % 2 );
number = number / 2;
printf ( "%d", number % 2 );
number = number / 2;
printf ( "\n" );
return 0;
}
OS: Fedora 20
Debugger gdb
I created a general C project (minimal)

Found out how to do it:
At least there needs to be a Makefile which can be used by gdb. The one created by Anjuta when creating a new C Makefile project can be used as basis.
Also, gdb needs to be enabled in the settings window.
1.Click "Add breakpoint" in the toolbar
2.Execute > Debug program
Then the buttons become sensitive and you can step trough the code

Related

In what situation the output could go wrong like this?

I am trying to do the problem 200B on codeforces. I tested my code, and the output was all right. But when I uploaded it to the online judge system, I failed on the very first test case. It said my output was -0.000000000000, instead of 66.666666666667.
But I have compiled and run on Visual Studio C++ 2010, MacOS clang 13.0.0, and Linux GCC 6.3.0, the outputs were all the same as mine, 66.666666666667. I am very curious and want to figure out in what situation the output could be -0.000000000000.
On my computer,
Input:
3
50 50 100
Output:
66.666666666667
On the online judge system,
Input:
3
50 50 100
Participant's output
-0.000000000000
Jury's answer
66.666666666667
Checker comment
wrong answer 1st numbers differ - expected: '66.66667', found: '-0.00000', error = '1.00000'
#include <stdio.h>
int main(void)
{
int n;
double sumOrange = 0;
double sumDrink = 0;
scanf ("%d", &n);
while (n-- > 0) {
int m;
scanf("%d", &m);
sumOrange += m / 100.0;
sumDrink++;
}
printf("%.12lf\n", (sumOrange / sumDrink) * 100.0);
return 0;
}
I just don't understand why my output could be -0.000000000000. Please help, thanks.
Update: Tested on different versions of GCC (4.9, 5.1, 6.3), the wrong output does not appear. Guess the cause might lie in the specific implementation of printf.
The problem is because printf function in GNU gcc C11 does not support %.12lf format. It should be changed to %.12f For more information, you can read the article below:
Correct format specifier for double in printf

What is the cause for 'Segmentation fault (core dumped) '

I wrote a program to find the prime factors of a number using recursion. I am getting an run time error. What is the cause?
#include<stdio.h>
int main () {
int num , i = 2 ;
printf ( " Enter the number to find the prime factors\n ") ;
scanf ( "%d", &num ) ;
printf ( " The factors are :\n") ;
pf ( num , i ) ;
}
int pf ( int num , int i){
if ( num % i == 0 ){
if ( checkprime(i) == 1){
printf ( " %d " , i ) ;
num = num / i ;
}
}
if ( num > 1 ){
i++ ;
pf ( num , i ) ;
}
}
int checkprime ( int i){
int j ;
if (i==2)
return 1 ;
for ( j = 2 ; j < i ; j++ ){
if ( (i % j) == 0 )
return 0 ;
else
return 1 ;
}
if ( i==j )
return 1 ;
}
Sample run:
Enter the number to find the prime factors
12
The factors are :
Segmentation fault (core dumped)enter code here
This looks like a learning exercise you want to solve on your own, so I won’t be writing code for you. (If you try to plug the sample code here into your program without refactoring, it won’t work.)
In the spirit of teaching you to fish, the first thing you should do is compile without optimization, with debugging symbols, and with all warnings turned on. On gcc/clang/icc, the flags for that will be something like:
-std=c11 -Wall -Wextra -Wpedantic -Wconversion -g
This code should not even compile. You’re repeatedly falling through to the end of a function that does not return the void type, yet falls through with no return statement. Not only that, you define pf() and checkprime() after they are called with no prototype! That’s not the only bug, but let’s start there.
You’re technically supposed to have a return from main(), too, but so many programs don’t that the C committee just gave in and said it’s optional.
A good next step to catch a bug is to load the program in a debugger, put a breakpoint on the function you want to debug, and single-step through it.
When you do this, you see that the program goes into an infinite loop if you give it, let’s say, 4, and if you do give it an answer that terminates, such as pf(1, 2), it will fall through all the if blocks and never reach a return statement.
So you need to debug your algorithm, but first, you need to make sure that every path through your function reaches a return statement. (You might also, if you don’t actually need a return value, declare void pf(int, int).
One way I like to do this (but doesn’t seem to be common in C) is to write if-else-return with the ? operator, such as:
return (num <= 1) ? 1 : // No more factors.
(num % i == 0) ? pf( num/i, i ) : // Prime factor, with possible multiplicity.
pf( num, i+1 ); // Not a factor. Keep looking.
This of course doesn’t work here because it never prints the factors. (It’s based on functional-style code that isn’t supposed to have side-effects like doing I/O.) One way to fix it would be to rewrite with if/then/else. Another is to store the factors in a data structure such as a dynamic array or linked list, and return that. Another is to print before the complex return. Another is to have the branch that should print a factor call a mutually-recursive function that prints and then calls pf(). A really ugly hack that you shouldn’t do is to use the comma operator. Pick the one you like the best.
This has the advantage of being tail-recursive, so it might go into an infinite loop but will not cause a stack overflow.
If you don’t like this style, another approach that some shops use to prevent this bug from happening is to write the function with nested if blocks that set a variable like int to_return = UNSET;. Then, every branch sets to_return to the proper value and you can finish with something like
if (foo)
to_return = 1;
else
to_return = f(i);
asseert(to_return != UNSET);
return to_return;
That way, the compiler ensures that you’re returning from a valid branch, or if you do forget to set a return value along some path, crashes and tells you where and why, not “Segmentation fault (core dumped).”

Im having problems using stdin and NULL in eclipse

Here is my code that I am having issues with. The goal of the program is to scan in a bunch of doubles and perform some simple statistical operations on them. The line I am having the issue with is the fgets(). I have included the stdio.h, it's just not showing up in the code. My actual question is where are the stdin and NULL giving me issues when I though they were part of the language? The exact error I am getting is that both Symbol stdin and NULL could not be resolved.
/*
* simpleStats.c
*
* Created on: Sep 17, 2018
* Author: David Liotta
*/
#include <stdio.h>
#define BUFSIZE 256
int main(){
double n, max, min, sum, mean;
char line[BUFSIZE];
int numsRead = 0;
int numOfItems = 1;
n = -1;
max = n;
min = n;
sum = n;
while(n != 0 && fgets(line, BUFSIZE, stdin ) != NULL){
numsRead = sscanf(line, "%f", &n);
if(numsRead == 1 && n != 0){
numOfItems++;
if(n > max)
max = n;
if(n < min)
min = n;
sum = sum + n;
}
if(numsRead == 0)
printf("Bad input\n");
}
mean = sum / numOfItems;
printf("# of items: %i", numOfItems);
printf("\nSum: %f.3", sum);
printf("\nMax: %f.3", max);
printf("\nMin: %f.3", min);
printf("\nMean: %f.3", mean);
}
This code should compile. I suspect something might be wrong with your development environment.
Since you're running Eclipse, I'm assuming that your compiler is GCC. I may be wrong though.
Try to locate your compiler executable, and run the compilation by hand:
gcc -Wall -o simpleStats simpleStats.c
or, if you're on Windows:
gcc.exe -Wall -o simpleStats.exe simpleStats.c
You may have to specify the full path to gcc.exe, (depending on your environment, it might even be called something else; you may be able to retrieve the full path from the console window in Eclipse).
Pay close attention to the output. Copy/paste the full output verbatim in your original post if you can (do not rephrase the warnings / error messages).
I seldom use Eclipse, but with most IDEs you get to chose what kind of project you want to create. Make sure you selected something like "console application", the error you're referring to (stdin not being resolved) may suggest a linker error. Again, it's hard to tell without the exact GCC output.
A couple more things to check:
make sure your compiler and its dependencies are properly installed,
make sure that this compiler is targeted at Windows (or whatever OS you use), not at some exotic embedded platform,
most development environments come with a bunch of sample projects, see if you can build one.
The problem I was having ended up being the compiler not correctly reading the code. I used a different compiler, and with some minor syntax changes, the code worked fine.

Visual Studios 2010: 'File location'.exe is not recognized as internal or external command... (C program)

My Thermo professor assigned our class a computational project in which we have to calculate some thermodynamic functions. He provided us with some code to work off of which is a program that essentially finds the area under a curve between two points for the function x^2. The code is said to be correct and it looks correct to me. However, I've been having FREQUENT problems with all of my programs giving me the error "'File location'.exe is not recognized as internal or external command, operable programs or batch files." upon initial running of a project or [mostly] reopening projects.
I've been researching the problem for many hours. I tried adjusting the environmental variables like so many other sites suggested, but I'm either not doing it right or it's not working. All I keep reading about is people explaining the purpose of an .exe file and that I have to locate that file and open that. The problem is that I cannot find ANY .exe file. There is the project I created with the source.c file I created and wrote the program in. Everything else has lengthy extensions that I've never seen before.
I'm growing increasingly impatient with Visual Studios' inconsistent behavior lately. I've just made the switch from MATLAB, which although is an inferior programming language, is far more user friendly and easier to program with. For those of you interested in the code I'm running, it is below:
#include <stdio.h>
#include <iostream>
#include <math.h>
using namespace std;
double integration();
double integration()
{
int num_of_intervals = 4, i;
double final_sum = 0, lower_limit = 2, upper_limit = 3, var, y = 1, x;
x = (upper_limit - lower_limit) / num_of_intervals; // Calculating delta x value
if(num_of_intervals % 2 != 0) //Simpson's rule can be performed only on even number of intervals
{
printf("Cannot perform integration. Number of intervals should be even");
return 0;
}
for(i = 0 ; i < num_of_intervals ; i++)
{
if(i != 0) //Coefficients for even and odd places. Even places, it is 2 and for odd it is 4.
{
if(i % 2 == 0)
y = 2;
else
y = 4;
}
var = lower_limit + (i * x);// Calculating the function variable value
final_sum = final_sum + (pow(var, 2) * y); //Calculating the sum
}
final_sum = (final_sum + pow(upper_limit , 2)) * x / 3; //Final sum
return final_sum;
}
int main()
{
printf("The integral value of x2 between limits 2 and 3 is %lf \n" , integration());
system("PAUSE");
return 0;
}
Thanks in advance,
Dom

Automatic export of symbols array in C debugging (teaching purpose)

I need to teach C to children (10-15 years old, teaching is through a website) and I want to be able to show them a step by step execution of a program but I don't want them to use a debugger directly (too complex for them, they are total beginners).
My idea was to pre-compute all the needed data and to show it to them (with a cool javascript animation, with the current line in the code, the values of the variables and the standard output).
What I need is a way to run a debugger on a C code and to export the values of the variables at each possible step (no struct, just basic variables and arrays).
Is there any interface to gdb or some other debugger that can to that ?
For some context : we are training students for the IOI (International Olympiad in Informatics) though a website with courses, exercices (automatically corrected)...
The code (in C) can be edited , compiled, tested and submitted online (with a javascript editor). This way no need to install anything (at first) so more people can just "try it".
The basic "step by step" debugging was only to show the beginners how variables are modified, how a "for" or a "while" are working. The kind of stuff you can do on a whiteboard as a teacher. More advanced students will install some IDE and will/or not use the debugger.
So for the beginners we want them to be able to play, on the website, with some basic code (affectations, maths operations, function call,for,while,if) to "see things".
If you're limited to programs with specific input, or without input at all, you can maybe use gdb scripting, in something like this:
try.c (the input program):
#include <stdio.h>
int main()
{
int i;
for (i = 0; i < 10; i++)
{
printf("the number now is %d\n", i);
i++;
}
return 0;
}
trace.gdb (a basic gdb script):
break main
run
while 1
info locals
step
end
quit
the results of gdb -x trace.gdb -batch try
Breakpoint 1 at 0x40053c: file try.c, line 6.
Breakpoint 1, main () at try.c:6
6 for (i = 0; i < 10; i++)
i = 0
8 printf("the number now is %d\n", i);
i = 0
the number now is 0
9 i++;
i = 0
6 for (i = 0; i < 10; i++)
i = 1
8 printf("the number now is %d\n", i);
i = 2
the number now is 2
9 i++;
i = 2
6 for (i = 0; i < 10; i++)
i = 3
8 printf("the number now is %d\n", i);
i = 4
the number now is 4
9 i++;
i = 4
6 for (i = 0; i < 10; i++)
i = 5
8 printf("the number now is %d\n", i);
i = 6
the number now is 6
9 i++;
i = 6
6 for (i = 0; i < 10; i++)
i = 7
8 printf("the number now is %d\n", i);
i = 8
the number now is 8
9 i++;
i = 8
6 for (i = 0; i < 10; i++)
i = 9
11 return 0;
i = 10
12 }
i = 10
0x000000300161ebbd in __libc_start_main () from /lib/libc.so.6
No symbol table info available.
Single stepping until exit from function __libc_start_main,
which has no line number information.
Program exited normally.
trace.gdb:6: Error in sourced command file:
No frame selected.
There are ways to change gdb's output so you can perhaps tune the script to make the output parsable in a way that will allow you to make it something playable by javascript.
And you'll also need to make sure the program does not loop endlessly, probably by using convenience variables to limit number of while loops in the script.

Resources