C - Any way to initialize srand multiple times? - c

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

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);

My C code. How to prevent numbers in columns to repeat? [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 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

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].

Would somebody explain how to use pci_enable_device() in linux

I am starting to learn to write PCI driver and the first exercise i took was to find if a given device exists on the bus. After searching some books and internet, i was able to write down the below program which does work but i am not clear on few concepts.
1 /*
2 Program to find a device on the PCI sub-system
3 */
4 #define VENDOR_ID 0x8086
5 #define DEVICE_ID 0x7113
6
7 #include <linux/kernel.h>
8 #include <linux/module.h>
9 #include <linux/stddef.h>
10 #include <linux/pci.h>
11 #include <linux/init.h>
12 #include <linux/cdev.h>
13 #include <linux/device.h>
14
15 #define LOG(string...) printk(KERN_NOTICE string)
16
17 #define CDEV_MAJOR 227
18 #define CDEV_MINOR 0
19
20
21 MODULE_LICENSE("GPL");
22
23 struct pci_dev *pci_dev;
24 unsigned long mmio_addr;
25 unsigned long reg_len;
26 unsigned long *base_addr;
27
28 int device_probe(struct pci_dev *dev, const struct pci_device_id *id);
29 void device_remove(struct pci_dev *dev);
30
31 struct pci_device_id pci_device_id_DevicePCI[] =
32 {
33 {VENDOR_ID, DEVICE_ID, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
34 {} // end of list
35 };
36
37 struct pci_driver pci_driver_DevicePCI =
38 {
39 name: "MyPCIDevice",
40 id_table: pci_device_id_DevicePCI,
41 probe: device_probe,
42 remove: device_remove
43 };
44
45
46 int init_module(void)
47 {
48 struct pci_dev *pdev = NULL;
49 int ret = 0;
50
51 pci_register_driver(&pci_driver_DevicePCI);
52 pdev = pci_get_device(VENDOR_ID, DEVICE_ID, NULL);
53 if (pdev)
54 {
55 LOG("Device found ... ");
56 pci_dev = pdev;
57 }
58 else
59 {
60 LOG("Device not found ... ");
61 }
62 return ret;
63
64
65 }
66
67 void cleanup_module(void)
68 {
69 pci_unregister_driver(&pci_driver_DevicePCI);
70
71 }
72
73 int device_probe(struct pci_dev *dev, const struct pci_device_id *id)
74 {
75 int ret;
76 LOG("Devie probed");
77 ret = pci_enable_device(dev);
78 if (ret < 0 ) LOG("Failed while enabling ... ");
79
80 return ret;
81 }
82
83 void device_remove(struct pci_dev *dev)
84 {
85 pci_release_regions(dev);
86 pci_disable_device(dev);
87 }
Inside init_module() function, given user VID and DID device is found and if successful, struct pdev is pointing to the respective pci device. As i have read, probe() function kicks in as soon as the device is found.
Does this mean we always have to do pci_get_device() before calling the pci_enable_device()?
IMO, yes but if so, how do device_probe() get reference to dev structure even though i am not passing it?
If i am 100% sure that my device exists on the system, how can i call pci_enable_device() without registering?
I am currently referring LDD3 book where they explain all the calls but for a beginner i feel it misses out how to connect the dot. Does any one have pointers where widely used pci_xx() calls are explained with neat examples?
Your probe function is called by pci_register_driver, which searches for an unclaimed device with a matching device ID.
Your pci_get_device call happens after probe has returned, and is not needed.

sscanf not detecting the right numbers

I'm having a hard time using sscanf to scan hour and minutes from a list. Below is a small snip of the list.
1704 86 2:30p 5:50p Daily
1711 17 10:40a 2:15p 5
1712 86 3:10p 6:30p 1
1731 48 6:25a 9:30a 156
1732 100 10:15a 1:30p Daily
1733 6 2:15p 3:39p Daily
I've tried this, but it keeps getting me segmentation Fault.(I'm putting this information into structures).
for(i=0;i<check_enter;i++){
sscanf(all_flights[i],
"%d %d %d:%d%c %d:%d%c %s",
&all_flights_divid[i].flight_number,
&all_flights_divid[i].route_id,
&all_flights_divid[i].departure_time_hour,
&all_flights_divid[i].departure_time_minute,
&all_flights_divid[i].departure_time_format,
&all_flights_divid[i].arrival_time_minute,
&all_flights_divid[i].arrival_time_minute,
&all_flights_divid[i].arrival_time_format,
&all_flights_divid[i].frequency);
printf("%d ",all_flights_divid[i].flight_number);
printf("%d ",all_flights_divid[i].route_id);
printf("%d ",all_flights_divid[i].departure_time_hour);
printf("%d ",all_flights_divid[i].departure_time_minute);
printf("%c ",all_flights_divid[i].departure_time_format);
printf("%d ",all_flights_divid[i].arrival_time_hour);
printf("%d ",all_flights_divid[i].arrival_time_minute);
printf("%c ",all_flights_divid[i].arrival_time_format);
printf("%s\n",all_flights_divid[i].frequency);
}
This is how I declared it.
struct all_flights{
int flight_number;
int route_id;
int departure_time_hour;
int departure_time_minute;
char departure_time_format;
int arrival_time_hour;
int arrival_time_minute;
char arrival_time_format;
char frequency[10];
};
struct all_flights all_flights_divid[3000];
These are the results I get
1704 86 2 30 p 0 50 p Daily
1711 17 10 40 a 0 15 p 5
1712 86 3 10 p 0 30 p 1
1731 48 6 25 a 0 30 a 156
1732 100 10 15 a 0 30 p Daily
1733 6 2 15 p 0 39 p Daily
Small mistake, that might be the problem:
this:
&all_flights_divid[1].flight_number,
should be:
&all_flights_divid[i].flight_number,
// ^
Edit:
Also, you read arrival_time_minute twice, and not reading arrival_time_hour at all. Fix it and it should be OK.
Most of the results seem to be fine, except the first field.
Now if you check your code..
&all_flights_divid[1]
fix it with
&all_flights_divid[i]

Resources