My C code. How to prevent numbers in columns to repeat? [closed] - c

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 12 months ago.
Improve this question
Hi, I have a question. I want to print a list of odd numbers from 1 to 99 in 2 columns using C, but as you can see in the image, the numbers are repeating. I want the numbers to follow the sequence. Like: 1-3-5-7etc..., not 1-3-3-5-5-7... Hope someone can help me, thank you.
#include<stdio.h>
int main(){
int sum=0,i=1,k=0;
printf("List of odd numbers:\n");
while(i<99){
k=i;
i=i+2;
printf("%d\t%d\n",k,i);
}
for(i=1;i<=99;i++){
if(i%2!=0)
sum+=i;
}
printf("Sum is: %d",sum);
return 0;
}
This is the link image of the code

Print your current number and the next number (+2). Afterwards, increment the current number by two positions (+4).
#include <stdio.h>
int main(void) {
for (unsigned i = 1; i < 99; i += 4)
printf("%d\t%d\n", i, i + 2);
}
stdout:
1 3
5 7
9 11
13 15
17 19
21 23
25 27
29 31
33 35
37 39
41 43
45 47
49 51
53 55
57 59
61 63
65 67
69 71
73 75
77 79
81 83
85 87
89 91
93 95
97 99

Related

Why does my c code not add the correct null zero at the end like it is supposed to and keeps printing out code?

I do not know why my code does not seem to be working properly. I am reading from a file, and grabbing each line and from there I am using my own function to try and break down each of the lines and add them to character arrays in a structure and then add those structures to an array. But for whatever reason, when I am trying to indivudually print out the individual values for all of the information it keeps printing out all of it. From what I am seeing, for whatever reason even though my function strsub is supposed to add a '\0' at the end, it does not seem to be doing that. So every time I pass in the pointer to the begging of each of the character variables it does not stop until the end of the whole structure so it starts by printing out the whole string and then prints out less and less. Is that the problem that I really have or am I missing something else?
This is my code so far. I first just tried creating a struct and filling the array with each pass, but unfortunantly I had the same issue.
#define _CRT_SECURE_NO_WARNINGS // Since I want to strictly use ANSI C and not Microsoft C without getting the warning message, I'm adding this line of code before I include header files.
#include <stdio.h> // "#include" includes the contents of another file, commonly called header file, into the source code file.
#include <string.h>
#define MAX 100
FILE *fp, *csit;
void strsub(char buf[], char sub[], int start, int end);
void printArray(struct trainCartrain[]);
struct trainCar {
char car[10];
char type[2];
char weight[6];
char length[3];
char horsepower[3];
char numberInTrain[4];
};
int main() {
struct trainCar ar[7];
struct trainCar train;
// test and open input file and output file.;
if (!(fp = fopen("train.txt", "r"))) {
printf("train.txt could not be opened for input.");
exit(1);
}
if (!(csit = fopen("csit.txt", "w"))) {
printf("csit.txt could not be opened for output.");
exit(1);
}
int i = 0;
char buf[MAX];
while (!feof(fp)) {
fgets(buf, MAX, fp);
strsub(buf, train.car, 0, 9);
strsub(buf, train.type, 10, 11);
strsub(buf, train.weight, 12, 17);
strsub(buf, train.length, 18, 20);
strsub(buf, train.horsepower, 21, 23);
strsub(buf, train.numberInTrain, 24, 27);
printf("%s", train.car);
printf("%s", train.type);
ar[i] = train;
i++;
}
printArray(ar);
fclose(csit);
fclose(fp);
return 0;
}
void strsub(char buf[], char sub[], int start, int end) { //strsub () grabs a substring, sub, from a string, buf, given the start and end index within the string.
int i, j;
for (j = 0, i = start; i <= end; i++, j++) {
sub[j] = buf[i];
}
sub[j] = '\0';
//end with the null terminator character that signifies the end of a string.
}
My file is small and simple, textfile
Boxcar D 44000 55 16 45
Hopper B 23000 62 18 33
Tanker G 15000 45 30 12
Autocar A 30000 37 23 6
Livestock L 56500 50 18 19
Coalcar C 49300 53 22 100
Flatcar F 18000 66 15 25
and what it prints out is
Boxcar D 44000 55 16 45
D 44000 55 16 45
44000 55 16 45
55 16 45
16 45
45
Hopper B 23000 62 18 33
B 23000 62 18 33
23000 62 18 33
62 18 33
18 33
33
Tanker G 15000 45 30 12
G 15000 45 30 12
15000 45 30 12
45 30 12
30 12
12
Autocar A 30000 37 23 6
A 30000 37 23 6
30000 37 23 6
37 23 6
23 6
6
Livestock L 56500 50 18 19
L 56500 50 18 19
56500 50 18 19
50 18 19
18 19
19
Coalcar C 49300 53 22 100
Flatcar F 18000 66 15 25C 49300 53 22 100
Flatcar F 18000 66 15 2549300 53 22 100
Flatcar F 18000 66 15 2553 22 100
Flatcar F 18000 66 15 2522 100
Flatcar F 18000 66 15 25100
Flatcar F 18000 66 15 25Flatcar F 18000 66 15 25F 18000 66 15 2518000 66 15 2566 15 2515 2525
can someone please explain what I am doing wrong? I do have to use this function strsub for my class too.
I am just trying to get it to print out the individual charachter data and not the whole string each time. I think it is an issue with the terminating zero at the end and when I tried debugging it does not seem to be adding that for some reason. I don't know why though, if that is the problem.
strsub(buf, train.car, 0, 9); accesses train.car with index 0 till 9 in the loop and then index 10 outside, but that's already out of bounds for a char car[10];.
Solution:
Increase the size of all of your arrays by 1 to have space for the 0-terminator of the string.
Also have a look at Why is “while( !feof(file) )” always wrong? . It is not related to your problem, but you might run into that problem in the next minutes.
Instead of
while (!feof(fp)) {
fgets(buf, MAX, fp);
....
}
use
while (fgets(buf, MAX, fp)) {
....
}
You missed a space in void printArray(struct trainCartrain[]);. It should be void printArray(struct trainCar train[]); and moved to after the definition of struct trainCar.
You also have to #include <stdlib.h> to use exit(1);

C - Any way to initialize srand multiple times?

Is there any way to initialize srand multiple times? I have an specific function to generate random numbers but every time i call it gives the same number. Any way to fix this?
int whoatk2() {
srand(time(NULL));
int a;
a = rand() % 50;
return a;
}
Unless you want a specific sequence, you should be calling srand once, and with a effectively arbitrary value like time(NULL). This would usually be done when your program starts.
If you call it every time you want a random number, you run the very real risk of initialising the generator with the same value each time (if you're calling it many times per second) and therefore getting the same "random" value each time.
This is the sort of thing you should be doing:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
srand(time(NULL)); // do this once
for (int i = 0; i < 10; ++i) { // do this many times
printf("%d\n", rand());
}
return 0;
}
Sample output is shown below, with the left column containing the output for the correct code above, and the right column containing the result of moving the srand call to inside the loop as you currently have (swapping the two lines that have comments above):
966271109 74846356
1059160369 74846356
1868029595 74846356
758240870 74846356
1795677958 74846356
806788680 74846356
1374271653 74846356
1658543317 74846356
1843517305 74846356
1568992484 74846356
srand is the function to initialize the pseudo-random generator with a seed, and rand is the function to get a random number from the generator...
You get the same random number repeatedly because you reinitialize the random number generator with the same seed every time you call whoatk2, which happens many times during the same second. The sequence of pseudo-random numbers returned by rand() is completely determined by the value passed to srand().
You should call srand() just once at the beginning of the program, preferably with a value that varies faster than time(NULL). You can use timespec_get(), gettimeofday() or similar:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#ifdef TIME_UTC
void random_initialize(void) {
struct timespec ts;
timespec_get(&ts, TIME_UTC);
srand(ts.tv_nsec);
}
#else
#include <sys/time.h>
void random_initialize(void) {
struct timeval tv;
gettimeofday(&tv, NULL);
srand(tv.tv_usec);
}
#endif
int whoatk2(void) {
return rand() % 50;
}
int main() {
random_initialize();
for (int i = 0; i < 20; i++) {
printf("%d ", whoatk2());
}
printf("\n");
return 0;
}
Running 10 times:
36 33 35 31 8 32 1 5 30 23 20 8 5 35 47 10 14 26 34 40
32 49 33 16 28 31 22 6 32 33 45 44 17 32 18 38 8 34 28 38
48 38 35 49 25 18 40 3 38 3 36 46 12 26 21 16 15 48 34 39
49 33 9 28 24 39 4 32 33 9 29 23 10 29 41 24 12 33 35 33
5 40 49 16 22 47 27 15 29 39 35 32 28 23 39 35 19 24 10 0
5 45 33 24 4 28 48 40 32 22 27 45 32 11 35 28 0 37 32 9
36 3 38 16 12 25 14 27 30 31 0 49 41 40 39 5 23 26 40 8
11 9 21 15 34 0 13 47 49 47 33 21 3 42 16 19 32 32 33 15
14 2 27 26 19 15 5 41 32 49 48 31 20 12 39 16 15 19 32 20
3 2 34 32 47 24 34 21 0 28 6 48 44 16 6 46 40 48 20 13

I am not able to rectify errors in this C code which is accepting user input for filling a 2d array using scanf [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
My try
int *nb=(int *)malloc(ntc*sizeof(int));// no of bus
int barr[ntc][ntc];// bus route array
int *nc=(int *)malloc(ntc*sizeof(int));// no of city
int carr[ntc][ntc];// city array
scanf("%d",&ntc); // input -> test case
for(i=0;i<ntc;i++)
{
scanf("%d",&(nb[i])); // input -> no of bus
p=2*nb[i];
for(k = 0; k < p; k++)
{
scanf("%d", &(barr[i][k])); // input -> bus route array
}
scanf("%d", &nc[i]); // input -> no of city for which bus passing by count is to be determined
q=nc[i];
for(j = 0; j < q; j++)
{
scanf("%d", &(carr[i][j])); // input -> city array
}
}
I am accepting input for various test cases. For test case#1 I am taking input of nb,barr,nc,carr arrays. This continues for ntc no of test cases. Below i have written the input statement of the problem
The first line contains the number of test cases (T), after which T
cases follow each separated from the next with a blank line. For each
test case, The first line contains the number of GBuses.(N) Second
line contains the cities covered by them in the form a1 b1 a2 b2 a3
b3...an bn where GBus1 covers cities numbered from a1 to b1, GBus2
covers cities numbered from a2 to b2, GBus3 covers cities numbered
from a3 to b3, upto N GBuses. Next line contains the number of cities
for which GBus count needs to be determined (P). The below P lines
contain different city numbers.
Suppose now input is
2
4
15 25 30 35 45 50 10 20
2
15
25
10
10 15 5 12 40 55 1 10 25 35 45 50 20 28 27 35 15 40 4 5
3
5
10
27
Now when i am printing the values just for a sanity check what i am getting is very strange.
printf("no of test case %d\n",ntc);
for(i=0;i<ntc;i++)
{
printf("Case #%d\n",i+1);
printf("no of bus %d\n",nb[i]);
p=2*nb[i];
printf("bus route array");
for(j=0;j<p;j++)
{
printf(" %d ",barr[i][j]);
}
printf("\nno of city for which bus passing by count is to be determined %d \n",nc[i]);
q=nc[i];
printf("city array");
for(k=0;k<q;k++)
{
printf(" %d ",carr[i][k]);
}
printf("\n");
}
no of test case 2
Case #1
no of bus 4
bus route array 10 15 5 12 40 55 1 10
no of city for which bus passing by count is to be determined 2
city array 5 10
Case #2
no of bus 10
bus route array 10 15 5 12 40 55 1 10 25 35 45 50 20 28 27 35 15 40 4 5
no of city for which bus passing by count is to be determined 3
city array 5 10 27
The output for Case #1 bus route should be 15 25 30 35 45 50 10 20 and not 10 15 5 12 40 55 1 10 and for city route it should be 15 25 not 5 10
int *nb=(int *)malloc(ntc*sizeof(int)); // what is ntc?
int barr[ntc][ntc]; // what is ntc?
int *nc=(int *)malloc(ntc*sizeof(int)); // what is ntc?
int carr[ntc][ntc]; // what is ntc?
scanf("%d",&ntc); // input -> test case // oh
C cannot see into the future. It is not possible to allocate an array and determine its size later. You need to read ntc first, then use it.
You also need to enable your compiler warnings and make sure all your programs build warning-free. This error can be easily caught by the compiler.
As a side note, automatic variable-length arrays in C are dangerous since they can easily cause your program to overstep its stack size limit. Avoid them. Allocate all arrays of unknown size dynamically.

Error on line 26 "Called object type "int" is not function or function pointer? why is this occuring? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
"Type called object type 'int' is not a function or function pointer" the error is coming up on line 26 which is my formula.
I can't determine the origin of the error, please help.
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <math.h>
14
15 int main()
16 double p1, ac, at, p2, p3, ar, p;
17 int code;
18 p=(p1+p2+p3)/2;
19 setvbuf(stdout, NULL, _IONBF, 0);
20
21 while(1){
22 printf("Enter code and parameter(s) (Code=0 to Quit):");
23 scanf("%d%lf%lf%lf", &code, &p1, &p2, &p3);
24 if(code==0) break;
25 if(code==1){
26 ac=2*M_PI*(p1*p1);
27 printf("area of circle: %f", ac);
28 }
29 else if(code==2){
30 at=sqrt(p*(p-p1)*(p-p2)*(p-p3));
31 printf("area of triangle: %f", at);
32 }
33 else if(code==3){
34 ar=p1*p2;
35 printf("area of rectangle: %f", ar);
36 }
37 return EXIT_SUCCESS;
38 }
39 }
You're missing the opening brace after main:
int main() {
double p1, ac, at, p2, p3, ar, p;
...

bufbomb stack overflow failed

I'm using bufbomb.c to do some buffer overflow attack experimenting.
I successfully used gdb to debug the code. Howeverer; when I run the program directly, I get a "Segmentation fault (core dumped)" when I enter the characters to try the attack.
I used gcc (Ubuntu/Linaro 4.8.1-10ubuntu9) 4.8.1. to build the following.
//bufbomb.c
/* Bomb program that is solved using a buffer overflow attack */
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
/* Like gets, except that characters are typed as pairs of hex digits.
Nondigit characters are ignored. Stops when encounters newline */
char *getxs(char *dest)
{
int c;
int even =1; /* Have read even number of digits */
int otherd =0; /* Other hex digit of pair */
char*sp = dest;
while ((c = getchar()) != EOF && c !='\n') {
if (isxdigit(c)) {
int val;
if ('0'<= c && c <='9')
val = c -'0';
else if ('A'<= c && c <='F')
val = c -'A'+10;
else
val = c -'a'+10;
if (even) {
otherd = val;
even =0;
}
else {
*sp++= otherd *16+ val;
even =1;
}
}
}
*sp++='\0';
return dest;
}
/* $begin getbuf-c */
int getbuf()
{
char buf[12];
getxs(buf);
return 1;
}
void test()
{
int val;
printf("Type Hex string:");
val = getbuf();
printf("getbuf returned 0x%x\n", val);
}
/* $end getbuf-c */
int main()
{
int buf[16];
/* This little hack is an attempt to get the stack to be in a
stable position
*/
int offset = (((int) buf) &0xFFF);
int*space = (int*) alloca(offset);
*space =0; /* So that don't get complaint of unused variable */
test();
return 0;
}
Then I executed it under gdb:
...> gdb ./bugbomb
...
..run
Type Hex string:30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 d8 bf ff ff 9f 85 04 08 b0 86 04 08 30 31 32 33 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 ef be ad de
getbuf returned 0xdeadbeef
[Inferior 1 (process 13530) exited normally]
And then without gdb::
./bufbomb
Type Hex string:30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 d8 bf ff ff 9f 85 04 08 b0 86 04 08 30 31 32 33 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 ef be ad de
Segmentation fault (core dumped)
I am looking for some help to resolve the seg-fault.
Run it under gdb with a bigger buffer to see which address it's trying to access to guess the stack offset of the return address used by getbuf().
To bear with small differences in memory offsets that arise from the use of gdb, use a NOP-sled. Your attack buffer should look like this:
|RET ADDRESS x 30 | NOPS (0x90) x 1000 | SHELLCODE|.
The return address should point to the middle of the NOP-sled.
If the execution jumps anywhere in the sled, it will slide to the shellcode.
You are accessing memory that your process doesn't "own".
When you run gdb, the compiler adds stuff (like extra debug info).
You can bypass the segmentation fault by expanding the stack before you attempt the buffer overflow:
int expand_stack(int n_bytes)
{
char buf[n_bytes];
return buf[n_bytes-1]; // access the memory to make sure the optimiser doesn't remove buf.
}
And in main, add a call to expand_stack before you call test:
int main()
{
int buf[16];
/* This little hack is an attempt to get the stack to be in a
stable position
*/
int offset = (((int) buf) &0xFFF);
int*space = (int*) alloca(offset);
*space = expand_stack(200);
test();
return 0;
}
Note that your code still invokes undefined behaviour.
Note2: If your compiler doesn't support variable length arrays, just use a fixed array, buf[200].

Resources