0

Puzzling behaviour in C [SOLVED]

Hi. I'm trying to learn to code in C and I decided I'd try and implement a Sieve of Eratosthenes to practice. See code here: https://code.sololearn.com/cjgrBsHVTjrd/?ref=app The thing is that it always feels like printing a selection of garbage whenever I try printing the primes. Can anyone explain why this is happening? Also, I was trying larger values of n too, but a selection of values were giving Segmentation Fault, despite values either side running ok. What's the reason for that? Thanks in advance.

17th Feb 2021, 8:12 PM
Russ
Russ - avatar
5 Answers
+ 5
The problem is on line 16 and 55. You don't need to multiply the offset by `int_size`. When you add 'n' to a pointer of type X, `n * sizeof(X)` is added to the pointer. So, for example, if you add 2 to a pointer of int, it gives you the memory location at offset 2 * sizeof(int) = 8 bytes See this (it's in C++, but it's the same in C) https://code.sololearn.com/ceW49173Elyk/?ref=app The fix as I pointer out above, is to simply do *(primes_list+ i) OR prime_list[i] INSTEAD OF *(prime_list + i * int_size) (Same on line 55)
17th Feb 2021, 8:44 PM
XXX
XXX - avatar
+ 2
Russ you're welcome. I'd like to point out just a thing though, that on line 26 and 51, you're allocating memory using malloc(), but never freeing it. This is a memory leak. Although memory leaks won't affect the execution of the code or anything else actually, but they are considered bugs and can be problematic in large programd, and that is why you should always free the memory you allocate. There is a high chance you're aware of this, but I just thought I'll point it out in case it helps
17th Feb 2021, 9:28 PM
XXX
XXX - avatar
+ 1
Thanks XXX that has fixed it! I did try doing what you said before, but I think I must have done that on only one of those lines, as I started getting a load of 0s. Thank you!
17th Feb 2021, 8:49 PM
Russ
Russ - avatar
+ 1
XXX Thanks again. Constructive criticism always welcomed and I will endeavour to make a habit of freeing memory after allocating it. Many thanks.
17th Feb 2021, 9:32 PM
Russ
Russ - avatar
0
Are you sure you have implemented sieve correctly ? Have a look, https://cp-algorithms.com/algebra/sieve-of-eratosthenes.html
17th Feb 2021, 8:40 PM
Hima
Hima - avatar