The Code doesn't print the expected output, why? - c

The following code doesn't behave as expected ..
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdbool.h>
struct dest
{
char filename[20], keyword[20];
bool opened;
FILE * file;
};
void display_data(const struct dest p) {
printf("Keyword: %s, Filename: %s, Used: %s\n", p.keyword, p.filename, p.opened ? "Yes" : "No");
}
int main(int argc, char const *argv[])
{
// declaring variables
float lon, lat;
char info[80];
FILE *reader;
// checking required arguments
if ((argc+1) % 2 || argc < 2) {
fprintf(stderr, "Usage: %s file_to_read file_for_unknown type file type file ...\n", argv[0]);
return 2;
}
// opening the reader
if (!(reader = fopen(argv[1], "r"))) {
fprintf(stderr, "File can't be accessed: %s\n", argv[1]);
return 2;
}
// creating important globals
const short pairs = (argc-3)/2;
struct dest data[pairs];
struct dest other;
strcpy(other.filename, argv[2]);
other.opened = false;
// gathering data
short times = 4;
for(short i = 4; i < argc; i += 2) {
data[i-times].opened = false;
strcpy(data[i-times].keyword, argv[i-1]);
strcpy(data[i-times].filename, argv[i]);
times += 1;
}
// finally, scanning the file ..
struct dest *use_f; // pointer for the wanted destination ..
bool known;
while (fscanf(reader, "%f,%f,%79[^\n]", &lat, &lon, info)) {
// deciding which file to use ..
known = false;
for(short i=0; i < pairs; ++i) {
if (strstr(info, data[i].keyword)) {
known = true;
use_f = &data[i];
}
}
if (!(known)) {
use_f = &other;
}
// checking the file ..
if (!((*use_f).opened)) {
(*use_f).file = fopen((*use_f).filename, "w");
(*use_f).opened = true;
}
// writing to the file ..
fprintf((*use_f).file, "%f,%f,%s\n", lat, lon, info);
}
// closing all data streams, and informing user ..
for (short i=0; i < pairs; ++i) {
display_data(data[i]);
if (data[i].opened) {
fclose(data[i].file);
data[i].opened = false;
}
}
fclose(reader);
fclose(other.file);
return 0;
}
The command used to run it is this ..
./categorize spooky.csv other.csv UFO UFOS.csv # I get no output at all
It seems that the while loop doesn't actually end, which is mysterious, because the file (spooky.csv) is only 11 lines !
30.685163,-68.137207,Type=Yeti
28.304380,-74.575195,Type=UFO
29.132971,-71.136475,Type=Ship
28.343065,-62.753906,Type=Elvis
27.868217,-68.005371,Type=Goatsucker
30.496017,-73.333740,Type=Disappearance
26.224447,-71.477051,Type=UFO
29.401320,-66.027832,Type=Ship
37.879536,-69.477539,Type=Elvis
22.705256,-68.192139,Type=Elvis
27.166695,-87.484131,Type=Elvis
It just keeps writing to other.file, yet I don't know why ..
The program simply doesn't end, can anybody explain things to me ?

From the fscanf() manpage: "The value EOF is returned if an input failure occurs before any conversion (such as an end-of-file) occurs."
Here's a hint... EOF isn't equal to 0. Your while-loop never terminates.

Related

getting virtual memory address(vma) of linker symbols

I'm playing around the bfd library (<bfd.h>), and I was able to implement my own version of objdump -h on binary files by printing out sections, their vmas, size, etc. Now, I'm having trouble implementing nm. I'm able to use the bfd library to obtain all the different symbols of a binary executable file, but how can I get each symbol's (main, etc) vma using asection/asymbol struct data? Here's the code I have that prints out every symbol name:
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <bfd.h>
int main(int argc, char *argv[])
{
bfd *ibfd = NULL;
if (!argv[1])
{
printf("Please supply a second argument\n");
return -1;
}
else
{
// initialize bfd so we can use it
bfd_init();
// open the supplied argument file
const char *str = argv[1];
ibfd = bfd_openr(str, "elf64-x86-64");
// if issue opening
if (!ibfd)
{
bfd_perror("open failure\n");
return -1;
}
// if file isnt elf binary file
if (!bfd_check_format(ibfd, bfd_object))
{
printf("not an object file\n");
return -1;
}
int spaceNeeded = bfd_get_symtab_upper_bound(ibfd);
if (spaceNeeded < 0)
{
return -1;
}
else if (spaceNeeded == 0)
{
return 1;
}
asymbol **symTable = malloc(spaceNeeded);
long numSyms = bfd_canonicalize_symtab(ibfd, symTable);
if (numSyms < 0)
return -1;
for (int i = 0, count = 0; i < numSyms; i++)
{
printf("%s\n", symTable[i]->name);
}
bfd_close(ibfd);
}
// success code
return 1;
}
nm uses the function bfd_symbol_info to fetch the virtual memory addresses of the symbols. You can read the source code for that function to get an idea as to the implementation.
void
bfd_symbol_info (symbol, ret)
asymbol *symbol;
symbol_info *ret;
{
ret->type = bfd_decode_symclass (symbol);
if (bfd_is_undefined_symclass (ret->type))
ret->value = 0;
else
ret->value = symbol->value + symbol->section->vma;
ret->name = symbol->name;
}

Why does my program keep getting stuck while running the mandelbrot brainf*** program?

I wanted to improve my C skills, so I search some program's ideas.
Someone propose to create a simple Brainf*** interpreter and then a compiler. So here I am.
I created the interpreter and it works as expected, except with the Mandelbrot program:
A mandelbrot set fractal viewer in brainfuck written by Erik Bosman
+++++++++++++[->++>>>+++++>++>+<<<<<<]>>>>>++++++>--->>>>>>>>>>+++++++++++++++[[
>>>>>>>>>]+[<<<<<<<<<]>>>>>>>>>-]+[>>>>>>>>[-]>]<<<<<<<<<[<<<<<<<<<]>>>>>>>>[-]+
<<<<<<<+++++[-[->>>>>>>>>+<<<<<<<<<]>>>>>>>>>]>>>>>>>+>>>>>>>>>>>>>>>>>>>>>>>>>>
>+<<<<<<<<<<<<<<<<<[<<<<<<<<<]>>>[-]+[>>>>>>[>>>>>>>[-]>>]<<<<<<<<<[<<<<<<<<<]>>
>>>>>[-]+<<<<<<++++[-[->>>>>>>>>+<<<<<<<<<]>>>>>>>>>]>>>>>>+<<<<<<+++++++[-[->>>
>>>>>>+<<<<<<<<<]>>>>>>>>>]>>>>>>+<<<<<<<<<<<<<<<<[<<<<<<<<<]>>>[[-]>>>>>>[>>>>>
>>[-<<<<<<+>>>>>>]<<<<<<[->>>>>>+<<+<<<+<]>>>>>>>>]<<<<<<<<<[<<<<<<<<<]>>>>>>>>>
[>>>>>>>>[-<<<<<<<+>>>>>>>]<<<<<<<[->>>>>>>+<<+<<<+<<]>>>>>>>>]<<<<<<<<<[<<<<<<<
<<]>>>>>>>[-<<<<<<<+>>>>>>>]<<<<<<<[->>>>>>>+<<+<<<<<]>>>>>>>>>+++++++++++++++[[
>>>>>>>>>]+>[-]>[-]>[-]>[-]>[-]>[-]>[-]>[-]>[-]<<<<<<<<<[<<<<<<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<<[->>>>>>+<<<<<<<<<<<<<<<[<<<<<<<<<]>>>[-]+>>>>>>[>>>>>>
>>>]>[-]+<]]+>[-<[>>>>>>>>>]<<<<<<<<]>>>>>>>>]<<<<<<<<<[<<<<<<<<<]>>>>[-]<<<++++
+[-[->>>>>>>>>+<<<<<<<<<]>>>>>>>>>]>>>>>->>>>>>>>>>>>>>>>>>>>>>>>>>>-<<<<<<[<<<<
<<<<<]]>>>]
I don't understand why, but my program keeps getting stuck in some sort of endless loop. I try to debug it using gdb but it's hard to find the right breakpoint in order to see why it stuck.
The program is as follows:
#include <stdio.h>
#include <stdlib.h>
// Brainfuck instructions
// > Math stuff
#define INCR '+' // +1 on current MS
#define DECR '-' // -1 on current MS
// > Memory slot stuff
#define FORW '>' // Go to next MS
#define BACK '<' // Go to previous MS
// > Logic stuff
#define SJMP '[' // Loop till current MS value is equal to zero
#define EJMP ']' // Jump to the beginning of the loop
// > I/O stuff
#define PRTC '.' // Print character with MS value as ASCII code
#define GETC ',' // Get an user input ASCII character code
typedef unsigned char byte;
// The brainfuck program struct
typedef struct {
byte *values;
int size;
int index;
byte *loops_starts;
int loop_size;
int loop_index;
} BrainfuckProgram;
void initialize(BrainfuckProgram *bfp) {
bfp->values = malloc(bfp->size * sizeof(*bfp->values));
bfp->loops_starts = malloc(bfp->size * sizeof(*bfp->loops_starts));
}
int allocate_values(BrainfuckProgram *bfp) {
byte *newMem = realloc(bfp->values, bfp->size * sizeof(byte));
if (!newMem) {
return 1;
}
bfp->values = newMem;
return 0;
}
int allocate_new_loop(BrainfuckProgram *bfp) {
byte *newMem = realloc(bfp->loops_starts, bfp->loop_size * sizeof(byte));
if (!newMem) {
return 1;
}
bfp->loops_starts = newMem;
return 0;
}
void set_value(BrainfuckProgram *bfp, byte value) {
int tempValue = value < 0 ? 255: value % 256;
*(bfp->values + bfp->index) = tempValue;
}
int get_value(BrainfuckProgram *bfp) {
return *(bfp->values + bfp->index);
}
// FILE functions
int get_file_name(int argc, char *argv[], char** fname) {
if (argc == 1) {
printf("File name is missing\n");
return 1;
}
*fname = argv[1];
return 0;
}
int get_file_size(FILE *file) {
fseek(file, 0L, SEEK_END);
int size = ftell(file);
rewind(file);
return size;
}
// Main function
int main(int argc, char *argv[]) {
// Vector part
BrainfuckProgram bfp = {
.values = NULL,
.size = 1,
.index = 0,
.loops_starts = NULL,
.loop_index = 0,
.loop_size = 0
};
initialize(&bfp);
// FILE Part
char* fname = NULL;
int error = get_file_name(argc, argv, &fname);
if (error) {
goto exit;
}
// Create file variable
FILE *fin = NULL;
fin = fopen(fname, "r");
int size = get_file_size(fin);
// Create a char array of the right size
byte *prog = NULL;
prog = malloc(size * sizeof(*prog));
// Read 1 byte size times
fread(prog, 1, size, fin);
for (int i = 0; i < size; i++) {
byte current = *(prog+i);
switch (current) {
case INCR:
set_value(&bfp, get_value(&bfp) + 1);
break;
case DECR:
set_value(&bfp, get_value(&bfp) - 1);
break;
case FORW:
// if index+1 == size then we are at the
// last element of the vector cause
// size = index - 1
if (bfp.index+1 == bfp.size) {
bfp.size++;
int error = allocate_values(&bfp);
if (error) {
printf("an error occured while forwarding pointer");
goto close;
}
}
bfp.index++;
break;
case BACK:
// bfp.index == 0 then !bfp.index == true
if (!bfp.index) {
printf("can go back from index 0\n");
goto close;
}
bfp.index--;
break;
case SJMP:
if (bfp.loop_index == bfp.size) {
bfp.loop_size++;
int error = allocate_new_loop(&bfp);
if (error) {
printf("an error occured while forwarding pointer");
goto close;
}
}
bfp.loop_index++;
*(bfp.loops_starts + bfp.loop_index) = i;
break;
case EJMP:
if (bfp.loop_index == -1) {
printf("cannot go back");
goto close;
}
if (get_value(&bfp) != 0) {
i = *(bfp.loops_starts + bfp.loop_index);
} else {
bfp.loop_index--;
}
break;
case PRTC:
printf("%c", get_value(&bfp));
break;
case GETC:
; // Semicolon here because of the label error
byte buf;
scanf("%c", &buf);
set_value(&bfp, buf);
break;
}
}
close:
fclose(fin);
exit:
;
return 0;
}
I'd like to have some C related advice on what I have done wrong too.
The Mandelbrot program takes a decent time to run on a good interpreter. Yours, well, it isn't that good. That's why it "hangs" at the start.
Some good ideas that you had, performance-wise:
precalculating loops
Some bad ideas, performance-wise:
Using abstracted allocation functions instead of calling realloc
using scanf and printf instead of getchar and putchar
Some odd things that you did:
Manually truncating an unsigned char when wraparound is implicit
checking if an unsigned char is less than 0
using *(x + y) syntax instead of array indexing x[y]
I don't think you actually use those precalculated loops, if you do then probably not correctly
You also probably create a new precalculated loop every time you go over the loop again
Using the get_value and set_value functions instead of pointers (this will be a performance issue if you don't compile with optimizations)
A couple suggestions:
Try to avoid calling functions when you don't need to as much as possible.
Write a BrainFuck->C compiler using this reference.
On second thought, maybe you should try to debug this program instead.
You may also use my interpreter as a reference if you're OK with GPLv3. Note that it doesn't precalculate loops.

Output to both console and txt file

I think this is written in C, honestly don't know how to identify (if someone could give some tips it would be great). When the command rpt dumpvars 1234 is run in the console it returns the variables of machine/node 1234 to the screen. I want the same data output to a variables.txt file. Is there a simple one liner that I can add to do this?
The file is located here.
The portion of the data I am trying to get can be found on lines 7590-7623 as pasted here:
/*
* Display a node's main channel variables from the command line
*/
static int rpt_do_showvars(int fd, int argc, char *argv[])
{
int i,thisRpt = -1;
struct ast_var_t *newvariable;
if (argc != 3) return RESULT_SHOWUSAGE;
for(i = 0; i < nrpts; i++)
{
if(!strcmp(argv[2], rpt_vars[i].name))
{
thisRpt = i;
break;
}
}
if (thisRpt < 0)
{
ast_cli(fd, "Unknown node number %s.\n", argv[2]);
return RESULT_FAILURE;
}
i = 0;
ast_cli(fd,"Variable listing for node %s:\n",argv[2]);
ast_channel_lock(rpt_vars[thisRpt].rxchannel);
AST_LIST_TRAVERSE (&rpt_vars[thisRpt].rxchannel->varshead, newvariable,
entries) {
i++;
ast_cli(fd," %s=%s\n", ast_var_name(newvariable),
ast_var_value(newvariable));
}
ast_channel_unlock(rpt_vars[thisRpt].rxchannel);
ast_cli(fd," -- %d variables\n", i);
return(0);
}

C: map a command-line arg to a compile-time constant

I'm writing a C program that accepts a system resource name (e.g. RLIMIT_NOFILE) and prints some resource limit info for it.
The resource constants are defined in <sys/resource.h>, e.g.
#define RLIMIT_NOFILE 5
I'm looking for a good way to map the command-line argument (e.g. RLIMIT_NOFILE) to the corresponding numeric value (e.g. 5).
I originally planned to do something like:
int resource = -1;
char *resource_names[] = {
"RLIMIT_NOFILE", "RLIMIT_NPROC", "RLIMIT_RSS"
};
for (i = 0; i < sizeof(resource_names)/sizeof(char *); i++) {
if (strcmp(argv[1], resource_names[i]) == 0) {
resource = eval(resource_names[i]);
break;
}
}
But C doesn't seem to have anything like eval, and even if it did, the compile-time constants wouldn't be available at run-time.
For now, I'm doing the following, but I'm curious if there's a better approach.
#include <stdio.h>
#include <string.h>
#include <sys/resource.h>
int main(int argc, char *argv[])
{
if (argc != 2) {
printf("Usage: %s <resource>\n", argv[0]);
return 1;
}
char *resource_names[] = {
"RLIMIT_NOFILE", "RLIMIT_NPROC", "RLIMIT_RSS"
};
int resources[] = {
RLIMIT_NOFILE, RLIMIT_NPROC, RLIMIT_RSS
};
int i, resource = -1;
for (i = 0; i < sizeof(resources)/sizeof(int); i++) {
if (strcmp(argv[1], resource_names[i]) == 0) {
resource = resources[i];
break;
}
}
if (resource == -1) {
printf("Invalid resource.\n");
return 1;
}
struct rlimit rlim;
getrlimit(resource, &rlim);
printf("%s: %ld / %ld\n", argv[1], rlim.rlim_cur, rlim.rlim_max);
return 0;
}
The RLIMIT_x constants are all low-value integers that can be used as indexes into an array, or (for your problem) use an array to find the index and it will correspond to the value you want.
Or you could have an array of structures, containing both the value and the string. Something like
static const struct
{
int limit;
char *name;
} rlimits[] = {
{ RLIMIT_NOFILE, "RLIMIT_NOFILE" },
{ RLIMIT_NPROC, "RLIMIT_NPROC" },
// Etc.
};
Then it's easy to iterate over the array and "map" a string to a value (or do the opposite).

The following code doesn't work .. why?

The following code isn't working as expected ..
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdbool.h>
struct dest
{
char filename[20], keyword[20];
bool opened;
FILE * stream;
};
void display_data(const struct dest p) {
printf("Keyword: %s, Filename: %s, Used: %s\n", p.keyword, p.filename, p.opened ? "Yes" : "No");
}
int main(int argc, char const *argv[])
{
// float lon, lat;
// char info[80];
if ((argc+1) % 2) {
fprintf(stderr, "Usage: %s file_to_read file_for_unknown type file type file ...\n", argv[0]);
return 2;
}
if (access(argv[1], F_OK) == -1) {
fprintf(stderr, "File can't be accessed: %s\n", argv[1]);
return 2;
}
const short pairs = (argc-3)/2;
struct dest data[pairs];
short times = 4;
for(short i = 4; i < argc; i += 2) {
struct dest data[i-times];
data[i-times].opened = false;
strcpy(data[i-times].keyword, argv[i-1]);
strcpy(data[i-times].filename, argv[i]);
// display_data(data[i-times]);
times += 1;
}
display_data(data[0]);
return 0;
}
That's what happens when I try to run it ..
./categorize spooky.csv other.csv UFO UFOS.csv
Keyword: ?, Filename: �#, Used: No
Which isn't that meaningful ..
I have been trying to work out the solution .. in vein ..
I don't understand where the problem is ..
Arguments are parsed as follows:
The first argument: the file the program is supposed to read from (ignored for now)
The second argument: the file the program is supposed to store at any unknown info found in the spooky.csv file (also, ignored in this implementation)
The other arguments: they are parsed as pairs, the first is the keyword, the second is the file ..
My Solution for this filtering problem was to create an array of structs, and within each struct I store the keyword, the filename and the file io stream (which i am ignoring, for now) ..
Any help would be highly appreciated ..
You have 2 struct dest data[] arrays. The inner one is masking the outer - get rid of it.
Your compiler is probably warning about this, if you have warnings turned on.

Resources