I only used C 2-3 times. Following hello world tutorial did not help. the function should just print to std out console.
#include <stdio.h>
void my_putstr(char* param_1) {
char *t ;
for (t = param_1; *t != '\0'; t++) {
printf("%s", t);
}
}
int main(){
my_putstr("abc");
return 0;
}
How to run this program? I do have main to call & test my putstr function.
I do this:
gcc file.c -o file
gcc file
But it still gives me the error of "main":
(.text+0x20): undefined reference to `main'
collect2: error: ld returned 1 exit status
I do have the main function. What's wrong?
gcc file.c -o file
gcc file
That second line will try to compile the executable file that you created with the first line and, since it's not C source(a), that won't end too well :-)
You need to run the file with something like:
./file
And, just as an aside, you should strive to make your programs more readable, such as with:
#include <stdio.h>
// my_putstr:
// Output the given string multiple times, each time starting
// at the next character. So, for "1234", it would output
// "1234 234 34 4" (without the spaces).
void my_putstr(char *str) {
// Start at position 0, 1, m2, etc until no more string left.
for (char *ptr = str; *ptr != '\0'; ptr++) {
printf("%s", ptr);
}
}
int main(void) {
my_putstr("abc");
return 0;
}
Changes made:
Comments are quite handy if you ever come back to the code after some time;
You should try to avoid simple variable names, use names that make the intent clear (about the only exception are simple i, j, k loop variables;
The two canonical forms of main are int main(int argc, char **argv) (though the "or equivalent" phrase in the standard also allows for int main(int argc, char *argv[])) or int main(void), you should try to stick with them.
By the way, the description in the comments above is an accurate representation of the way the code works. If, instead, you just want to output a string (i.e., not the 1234 234 34 4 behaviour), you're probably better off with something like:
void my_putstr(char *str) {
// Output each character, one at a time.
for (char *ptr = str; *ptr != '\0'; ptr++)
putchar(*ptr);
// Output newline (if desired).
putchar('\n');
}
(a) The gcc program is quite capable of taking other input file types (like object files, assembler files, and so on) but I'm not sure finished executables are one of those types.
Related
I'm trying to build a C program that will bruteforce a hash given in argument. Here is the code:
#include <unistd.h>
#include <stdio.h>
#include <crypt.h>
#include <string.h>
const char setting[] = "$6$QSX8hjVa$";
const char values[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
int main(int argc, char *argv[])
{
char *hashToCrack = crypt(argv[1], setting);
printf("%s\n", hashToCrack);
for (int i = 0; i < strlen(values); i++)
{
printf("trying %c ...\n", values[i]);
char *try = crypt(&values[i], setting);
if (strcmp(hashToCrack, try) == 0)
{
printf("calc: %s\n", try);
printf("init: %s\n", hashToCrack);
printf("Found!\n");
}
}
return 0;
}
For convenience, I just give in argument a string that will be the one to crack. It is encrypted at the beginning of the main function (stored in hashToCrack). For now, I just work with one char. I compile the program this way: gcc main.c -o main -lcrypt -Wall.
The problem - When I launch this program, I have "Found!" in every iteration in the for loop. It seems that hashToCrack and try are the same. However, I never overwrite hashToCrack, so it should never change.
There is probably something I don't understand with pointers, but I can't find it.
Any idea ? :D
The crypt function returns a pointer to a static data buffer. So when you call it again, the string pointed to by hashToCrack changes.
You need to copy the results of the first call to crypt into a separate buffer.
char *hashToCrack = strdup(crypt(argv[1], setting));
Don't forget to call free on this buffer when you're done with it.
This is my main file
#include<stdio.h>
#include<string.h>
#include "ssv.c"
int main() {
int i,length,acct;
float amnt;
char data[1000], record[1000];
FILE *x = fopen("students.ssv","rt");
while(!feof(x)) {
for (i = 0; data[i] != '\n'; i++) {
record[i] = data[i];
length = i + 1;
}
record[length] = '\0';
parse(record,&acct,&amnt);
fgets(data,999,x);
}
fclose(x);
return 0;
}
This is my ssv.c file
#include<stdio.h>
void parse(char record[], int *acct, float *amnt){
sscanf(record,"%d %f",acct,amnt);
}
For some reason, these two programs are not working very well together. I am still getting used to modular programming. I keep getting the messages "undefined reference to main" and "multiple definition of".
My main goal here is to parse a file like
100 -10.5
13 -2.4
into corresponding fields. Please advise!
The first iteration of the while loop uses data before it has read the line. It should be:
while(fgets(data, sizeof data, x)) {
parse(data,&acct,&amnt);
}
You don't need to subtract 1 from the size of data when calling fgets().
There's no reason to copy data to record. You can simply parse data (the parse() function will ignore the newline). fgets() ends the string with a null terminator, you don't need to add it yourself.
#include should only be used for .h files, not .c files. You combine object files using the linker. So get rid of #include "ssv.c", replace it with #include "ssv.h". This file should just contain a declaration of parse().
void parse(char record[], int *acct, float *amnt);
Compile the two programs using:
gcc main.c ssv.c
Or you can compile each file separately then link them:
gcc -c main.c
gcc -c ssv.c
gcc main.o ssv.o
I'm trying my luck with C lately and I came across to this question where I'm stuck.
I've a hello.c file
CODE 1
#include<stdio.h>
#include<stdlib.h>
int main(){
printf("Hello World");
return 0;
}
I open this file and display the content using the following C program (CODE 2)
CODE 2
#include<fcntl.h>
#include<stdio.h>
int main() {
FILE *fd;
char ch;
fd = fopen("/home/hello.c","r");
if( fd != NULL ) {
while((ch = getc( fd )) != EOF){
putchar(ch);
}
}
return 0;
}
However, I want the output of this code to be Hello World, i.e output of the hello.c file which is read.
How can that be done?
In order to run a c file, first you need to compile it into machine code then execute it.
To compile it: run gcc source-file -o executable-file
To run, execute: executable-file
In order to to the same things in C, use system() function from <stdlib.h>
const char* tempFile = "./tempfile";
const char* sourceFile = "hello.c";
const char compileCommand[255];
sprintf(compileCommand, "gcc %s -o %s", sourceFile, tempFile);
system(compileCommand);
system(tempFile);
This code hasn't been tested.
Currently, in the second program, you are reading hello.c file. So the output of CODE2 will be the contents of hello.c. i.e. #include<stdio.h>...
For what you need, in CODE1, you need to write the output of the program into a separate file (say a.txt) and then read a.txt in CODE2.
Hope this is a sufficient hint for you to solve further.
Your "CODE 2" would have to invoke a C-compiler to compile "CODE 1" and then run it using system() or a function provided by your operating system.
BTW: It is either int main(void) or int main(int argc, char** argv), NOT int main().
As general solution, you may try also to have a look to a C interpreter, like Cling, and try to include it in your project.
I have made little program for computing pi (π) as an integral. Now I am facing a question how to extend it to compute an integral, which will be given as an extra parameter when starting an application. How do I deal with such a parameter in a program?
When you write your main function, you typically see one of two definitions:
int main(void)
int main(int argc, char **argv)
The second form will allow you to access the command line arguments passed to the program, and the number of arguments specified (arguments are separated by spaces).
The arguments to main are:
int argc - the number of arguments passed into your program when it was run. It is at least 1.
char **argv - this is a pointer-to-char *. It can alternatively be this: char *argv[], which means 'array of char *'. This is an array of C-style-string pointers.
Basic Example
For example, you could do this to print out the arguments passed to your C program:
#include <stdio.h>
int main(int argc, char **argv)
{
for (int i = 0; i < argc; ++i)
{
printf("argv[%d]: %s\n", i, argv[i]);
}
}
I'm using GCC 4.5 to compile a file I called args.c. It'll compile and build a default a.out executable.
[birryree#lilun c_code]$ gcc -std=c99 args.c
Now run it...
[birryree#lilun c_code]$ ./a.out hello there
argv[0]: ./a.out
argv[1]: hello
argv[2]: there
So you can see that in argv, argv[0] is the name of the program you ran (this is not standards-defined behavior, but is common. Your arguments start at argv[1] and beyond.
So basically, if you wanted a single parameter, you could say...
./myprogram integral
A Simple Case for You
And you could check if argv[1] was integral, maybe like strcmp("integral", argv[1]) == 0.
So in your code...
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
if (argc < 2) // no arguments were passed
{
// do something
}
if (strcmp("integral", argv[1]) == 0)
{
runIntegral(...); //or something
}
else
{
// do something else.
}
}
Better command line parsing
Of course, this was all very rudimentary, and as your program gets more complex, you'll likely want more advanced command line handling. For that, you could use a library like GNU getopt.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
int i, parameter = 0;
if (argc >= 2) {
/* there is 1 parameter (or more) in the command line used */
/* argv[0] may point to the program name */
/* argv[1] points to the 1st parameter */
/* argv[argc] is NULL */
parameter = atoi(argv[1]); /* better to use strtol */
if (parameter > 0) {
for (i = 0; i < parameter; i++) printf("%d ", i);
} else {
fprintf(stderr, "Please use a positive integer.\n");
}
}
return 0;
}
Parsing command line arguments in a primitive way as explained in the above answers is reasonable as long as the number of parameters that you need to deal with is not too much.
I strongly suggest you to use an industrial strength library for handling the command line arguments.
This will make your code more professional.
Such a library for C++ is available in the following website. I have used this library in many of my projects, hence I can confidently say that this one of the easiest yet useful library for command line argument parsing. Besides, since it is just a template library, it is easier to import into your project.
http://tclap.sourceforge.net/
A similar library is available for C as well.
http://argtable.sourceforge.net/
There's also a C standard built-in library to get command line arguments: getopt
You can check it on Wikipedia or in Argument-parsing helpers for C/Unix.
Here what's i am trying to do:
assume you have two fonction
void f1(int *v)
{
*v = 55;
}
void f2(int *v)
{
*v = 44;
}
char *template;
template = allocExecutablePages(...);
char *allocExecutablePages (int pages)
{
template = (char *) valloc (getpagesize () * pages);
if (mprotect (template, getpagesize (),
PROT_READ|PROT_EXEC|PROT_WRITE) == -1) {
perror (“mprotect”);
}
}
I would like to do a comparison between f1 and f2 (so tell what is identical and what is not) (so get the assembly lines of those function and make a line by line comparison)
And then put those line in my template.
Is there a way in C to do that?
THanks
Update
Thank's for all you answers guys but maybe i haven't explained my need correctly.
basically I'm trying to write a little obfuscation method.
The idea consists in letting two or more functions share the same location in memory. A region of memory (which we will call a template) is set up containing some of the
machine code bytes from the functions, more specifically, the ones they all
have in common. Before a particular function is executed, an edit script is used
to patch the template with the necessary machine code bytes to create a
complete version of that function. When another function assigned to the same
template is about to be executed, the process repeats, this time with a
different edit script. To illustrate this, suppose you want to obfuscate a
program that contains two functions f1 and f2. The first one (f1) has the
following machine code bytes
Address Machine code
0 10
1 5
2 6
3 20
and the second one (f2) has
Address Machine code
0 10
1 9
2 3
3 20
At obfuscation time, one will replace f1 and f2 by the template
Address Machine code
0 10
1 ?
2 ?
3 20
and by the two edit scripts e1 = {1 becomes 5, 2 becomes 6} and e2 = {1
becomes 9, 2 becomes 3}.
#include <stdlib.h>
#include <string.h>
typedef unsigned int uint32;
typedef char * addr_t;
typedef struct {
uint32 offset;
char value;
} EDIT;
EDIT script1[200], script2[200];
char *template;
int template_len, script_len = 0;
typedef void(*FUN)(int *);
int val, state = 0;
void f1_stub ()
{
if (state != 1) {
patch (script1, script_len, template);
state = 1;
}
((FUN)template)(&val);
}
void f2_stub () {
if (state != 2) {
patch (script2, script_len, template);
state = 2;
}
((FUN)template)(&val);
}
int new_main (int argc, char **argv)
{
f1_stub ();
f2_stub ();
return 0;
}
void f1 (int *v) { *v = 99; }
void f2 (int *v) { *v = 42; }
int main (int argc, char **argv)
{
int f1SIZE, f2SIZE;
/* makeCodeWritable (...); */
/* template = allocExecutablePages(...); */
/* Computed at obfuscation time */
diff ((addr_t)f1, f1SIZE,
(addr_t)f2, f2SIZE,
script1, script2,
&script_len,
template,
&template_len);
/* We hide the proper code */
memset (f1, 0, f1SIZE);
memset (f2, 0, f2SIZE);
return new_main (argc, argv);
}
So i need now to write the diff function. that will take the addresses of my two function and that will generate a template with the associated script.
So that is why i would like to compare bytes by bytes my two function
Sorry for my first post who was not very understandable!
Thank you
Do you want to do this at runtime or during authorship?
You can probably instruct your C compiler to produce assembly language output, for example gcc has the -S option which will produce output in file.s Your compiler suite may also have a program like objdump which can decompile an object file or entire executable. However, you generally want to leave optimizations up to a modern compiler rather than do it yourself.
At runtime the & operator can take the address of a function and you can read through it, though you have to be prepared for the possibility of encountering a branch instruction before anything interesting, so you actually have to programatically "understand" at least a subset of the instruction set. What you will run into when reading function pointers will of course vary all over the place by machine, ABI, compiler, optimization flags, etc.
Put the functions into t1.c and t2.c use gcc -S to generate assembly output:
gcc -S t1.c
gcc -S t2.c
Now compare t1.s and t2.s.
If you are using Visual Studio, go to
Project Properties -> Configuration -> C/C++ -> Output Files -> Assembler output
or use compiler switches /FA, /FAc, /FAs, /FAcs. Lower-case c means output machine code, s-source code side-by-side with assembly code. And don't forget to disable compiler optimizations.
Having read through some of the answers and the comments there, I'm not sure I fully understand your question, but maybe you're looking for a gcc invocation like the following:
gcc -S -xc - -o -
This tells gcc to input C code from stdin and output assembly to stdout.
If you use a vi-like editor, you can highlight the function body in visual mode and then run the command:
:'<,'>!gcc -S -xc - -o - 2> /dev/null
...and this will replace the function body with assembly (the "stderr > /dev/null" business is to skip errors about #include's).
You could otherwise use this invocation of gcc as part of a pipeline in a script.