Why did I get the same result after using rand()?

Asked by guoronghua on 2019-10-18

I use the 4.8 2014 q3. In my program, everytime I called rand(), the results were the same.

I tried to call srand(seed), but it didn't work. The output of rand() didn't change..

Please help me.

Question information

Language:
English Edit question
Status:
Answered
For:
GNU Arm Embedded Toolchain Edit question
Assignee:
No assignee Edit question
Last query:
2019-10-18
Last reply:
2019-10-18
Manfred Hampl (m-hampl) said : #1

Which seed value are you using?
If you usea constant value for seed, you will always receive the same row of rand() values.

Usually you should use something like

#include <time.h>

  srand (time(NULL));

to initialize the random generator with a value that is different in every execution.

guoronghua (rhguo) said : #2

I am using different seeds.

I get the same value every rand()

0011a774 <srand>:
  11a774: 4b02 ldr r3, [pc, #8] ; (11a780 <srand+0xc>)
  11a776: 2100 movs r1, #0
  11a778: 681b ldr r3, [r3, #0]
  11a77a: e9c3 012a strd r0, r1, [r3, #168] ; 0xa8
  11a77e: 4770 bx lr
  11a780: 00200430 .word 0x00200430

0011a784 <rand>:
  11a784: b430 push {r4, r5}
  11a786: 4b0c ldr r3, [pc, #48] ; (11a7b8 <rand+0x34>)
  11a788: 4d0c ldr r5, [pc, #48] ; (11a7bc <rand+0x38>)
  11a78a: 681c ldr r4, [r3, #0]
  11a78c: 490c ldr r1, [pc, #48] ; (11a7c0 <rand+0x3c>)
  11a78e: f8d4 20a8 ldr.w r2, [r4, #168] ; 0xa8
  11a792: f8d4 00ac ldr.w r0, [r4, #172] ; 0xac
  11a796: fb05 f502 mul.w r5, r5, r2
  11a79a: fba2 2301 umull r2, r3, r2, r1
  11a79e: fb01 5100 mla r1, r1, r0, r5
  11a7a2: 3201 adds r2, #1
  11a7a4: 440b add r3, r1
  11a7a6: f143 0300 adc.w r3, r3, #0
  11a7aa: e9c4 232a strd r2, r3, [r4, #168] ; 0xa8
  11a7ae: f023 4000 bic.w r0, r3, #2147483648 ; 0x80000000
  11a7b2: bc30 pop {r4, r5}
  11a7b4: 4770 bx lr
  11a7b6: bf00 nop
  11a7b8: 00200430 .word 0x00200430
  11a7bc: 5851f42d .word 0x5851f42d
  11a7c0: 4c957f2d .word 0x4c957f2d

Manfred Hampl (m-hampl) said : #3

What is the part of the source code where us call rand and srand?

Manfred Hampl (m-hampl) said : #4

oops, typo with wrong autocorrect ... where you call ...

guoronghua (rhguo) said : #5

I run the program on cm3, did I link the wrong libc.a? which one libc.a should I link?

srand(HW_TIME); the seed was got from HW register.
printf("%d,%d,%d", rand(), rand(), rand()); the three value were the same.

guoronghua (rhguo) said : #6

I linked
4.8 2014q3\lib\gcc\arm-none-eabi\4.8.4\armv7-m for libgcc.a
4.8 2014q3\arm-none-eabi\lib\armv7-m for libc.a

Can you help with this problem?

Provide an answer of your own, or ask guoronghua for more information if necessary.

To post a message you must log in.