Register for your free account! | Forgot your password?

Go Back   elitepvpers > Coders Den > C/C++
You last visited: Today at 07:45

  • Please register to post and access all features, it's quick, easy and FREE!

Advertisement



Calculating the Average of Numbers

Discussion on Calculating the Average of Numbers within the C/C++ forum part of the Coders Den category.

Reply
 
Old   #1
 
elite*gold: 26
Join Date: Sep 2012
Posts: 2,499
Received Thanks: 171
Calculating the Average of Numbers

Hello Guys,

can someone explain how i calculate the average of numbers entered by the user with a dynamic array?

I am really bad in programming so it would be nice if
someone could help me..



KeinDing. is offline  
Old 10/30/2018, 00:39   #2
 
elite*gold: 100
Join Date: Apr 2008
Posts: 678
Received Thanks: 921
C
  1. the user how many values he's going to enter
  2. Allocate some memory using
  3. from the user and store the values inside the allocated memory
  4. Iterate through the list
  5. Sum up all values and divide them by the number of values

C++
  1. Read in the numbers from the user and store them in a or a
  2. through all values of the vector or list
  3. Sum all values up and divide them by the number of values


florian0 is offline  
Old 10/30/2018, 14:22   #3
 
elite*gold: 0
Join Date: Feb 2009
Posts: 1,120
Received Thanks: 548
Quote:
Originally Posted by florian0 View Post
Allocate some memory using malloc
what a normie, cool kids use so you don't have to free up the memory
warfley is offline  
Old 10/06/2019, 17:38   #4
 
elite*gold: 0
Join Date: Dec 2014
Posts: 420
Received Thanks: 189
Quote:
Originally Posted by warfley View Post
what a normie, cool kids use so you don't have to free up the memory
I know that this thread is old, however i would still not suggest using alloca for this kind of user scenario as alloca allocates memory on the stack frame, thus the memory on the stack frame will automatically be de-allocated once returned (like you mentioned). However, the memory on the stack frame is limited to the stack frame itself (obviously), meaning that it's not suited for larger allocations whereas malloc can deal with such large allocations since it uses the heap and not the stack for allocations.

just a little thought i wanted to leave here in this thread in case someone now tries to replace all of his malloc calls with allocs and wonders why they are getting seg faults :p


_asm is offline  
Thanks
1 User
Old 10/07/2019, 15:30   #5
 
elite*gold: 0
Join Date: Feb 2009
Posts: 1,120
Received Thanks: 548
Quote:
Originally Posted by _asm View Post
just a little thought i wanted to leave here in this thread in case someone now tries to replace all of his malloc calls with allocs and wonders why they are getting seg faults
This was more or less a joke, but if you want to you can easiely increase the stack limits
Linux:
Code:
ulimit -s unlimited
Win32:
Code:
editbin /STACK:4294967295 program.exe
and voiala stack limits aren't a problem anymore xD. If an ugly solution doesn't fit your needs, there is always an even more ugly hack to compensate for it

Also alloca has some advantages. Memory allocations via malloc are slow, especially if you have very fragmented memory. Stack allocations are literally only a single pointer increase, the fastest operation you can do.

But I feel the need to also say, alloca is not standardized, or to quote the man page:
Quote:
The alloca() function is machine- and compiler-dependent. For certain applications, its use can improve efficiency compared to the use of malloc(3) plus free(3). In certain cases, it can also simplify memory deallocation in applications that use longjmp(3) or siglongjmp(3). Otherwise, its use is discouraged.
But who cares about what the documentation says. Cool kidz use it anyway!
warfley is offline  
Thanks
1 User
Old 10/07/2019, 17:41   #6
 
elite*gold: 0
Join Date: Dec 2014
Posts: 420
Received Thanks: 189
Quote:
Originally Posted by warfley View Post
This was more or less a joke, but if you want to you can easiely increase the stack limits
Linux:
Code:
ulimit -s unlimited
Win32:
Code:
editbin /STACK:4294967295 program.exe
and voiala stack limits aren't a problem anymore xD. If an ugly solution doesn't fit your needs, there is always an even more ugly hack to compensate for it

Also alloca has some advantages. Memory allocations via malloc are slow, especially if you have very fragmented memory. Stack allocations are literally only a single pointer increase, the fastest operation you can do.

But I feel the need to also say, alloca is not standardized, or to quote the man page:

But who cares about what the documentation says. Cool kidz use it anyway!
great, now all people will increase their stack frame size and get away with it!
all jokes aside, for his needs a malloc is probably the way to go for a generic solution that is not bound to the stack size. alloca or some other magical automatic deallocation function that relies on the stack, which makes it faster (duh), would probably do the trick as well.

nonetheless, i wish discussions like that would happen more frequently because they tend to be a lot of fun lmao

kind regards,
_asm
_asm is offline  
Thanks
1 User
Old 10/07/2019, 18:15   #7
 
elite*gold: 0
Join Date: Nov 2018
Posts: 333
Received Thanks: 643
Y'all need some more in your lives.
sk8land​ is offline  
Old 10/07/2019, 18:38   #8
 
elite*gold: 0
Join Date: Feb 2009
Posts: 1,120
Received Thanks: 548
Quote:
RAII is a C++ programming technique
To quote
Quote:
C++ is to C as Lung Cancer is to Lung
(just kidding, c++ is great)
warfley is offline  
Old 10/27/2019, 01:16   #9
 
elite*gold: 14835
The Black Market: 169/0/0
Join Date: Jul 2009
Posts: 3,255
Received Thanks: 780
Quote:
Originally Posted by florian0 View Post
C
  1. the user how many values he's going to enter
  2. Allocate some memory using
  3. from the user and store the values inside the allocated memory
  4. Iterate through the list
  5. Sum up all values and divide them by the number of values
Hey! I just coded a simple Program with all your helpful instructions.

How does it look?

Code:
/* gcc (GCC) 9.2.0, GLIBC Version 2.30 (arch btw)
   Compiled with `gcc file.c` */
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

#define ARR_LEN 10


long int get_num(){
	long int num;

	if( (scanf("%ld",&num)) != 1){
		num = -1;
	}
	while ((getchar()) != '\n');
	return num;
}

long int *get_numbers(){
	/* we're in 2k19, we only want the big stuff */
	long int cnt, *data = 0, tmp;
	int ret = 0;
	
	/* Ask the user how many values he's going to enter */
	printf("How many values do you want to enter?\n>"); 
	cnt = get_num();
	
	/* Allocate some memory using [STRIKE]malloc[/STRIKE] calloc (is safer, they say)
	cnt + 1 to also store the cnt in data[0] */
	data = calloc(cnt + 1, sizeof(*data));

	if (data == NULL){
		printf("No, no...");
		exit(0);
	}
	data[0] = cnt;
	
	/* Read from the user and store the values inside the allocated memory */
	for(int i=1; i < cnt + 1; i++){
		if( (tmp = get_num()) == -1){
			break;
		}
		data[i] = tmp;
	}
	return data;
}

void print_average(long int **data){
	int idx = 0;
	long int sum = 0;
	
	printf("average at which idx?\n>");
	idx = get_num();

	if(!(0 <= idx < ARR_LEN) || data[idx] == NULL){exit(0);}

	/* Iterate through the list */
	for(int i = 1; i < (data[idx][0] + 1); i++){

                /* Sum up all values */
		sum += data[idx][i];	
	}

	/* and divide them by the number of values */
	printf("The average is: %lf\n",(double)sum / data[idx][0]);
}

void delete_numbers(long int ** numbers){
	int idx;
	
	printf("delete at which idx?\n>");
	idx = get_num();
		
	if(0 <= idx < ARR_LEN && numbers[idx] != NULL){
		free(numbers[idx]);	
		numbers[idx] = NULL;
	} else {
		printf("Try harder, lil fella\n");
	}
}

void print_menu(){
	printf("------------------\n");
	printf("What do?\n");
	printf("1) get numbers\n");
	printf("2) print_average\n");
	printf("3) delete_numbers\n>");
}

int get_next_index(long ** numbers){
	for(int i = 0; i < ARR_LEN; i++){
		if(numbers[i] == NULL){
			return i;
		}
	} 
	return -1;
}

int main(){
	int slot;
	long int *data;
	long int **numbers = calloc(ARR_LEN,sizeof(**numbers));

	int num, ret;

    setvbuf( stdout , NULL , _IONBF , 0);

	for(int i=0; i < 50; i++){

		print_menu();
		num = get_num();		

		switch(num){
			case 1:
				slot = get_next_index(numbers);

				if(slot == -1){
					printf("delete first plox\n");
					break;
				}

				data = get_numbers();
				numbers[slot] = data;
				break;

			case 2:
				print_average(numbers);
				break;

			case 3:
				delete_numbers(numbers);
				break;
				
			default:
				break;
		}	
	}
	free(numbers);
}
For some reason, i host this code on 46.101.210.6 port 1337.
If you can msg me with the contents of /chall/flag on this server, i will give you some e*g. Challenged is everyone who deems himself worthy. Please do not speak publicly about potential vulnerabilities/solutions here. PM me if you need any pointers.

@ @ @ @

Feel free to ping more people, looking forward to see some skills
Beni is offline  
Thanks
4 Users
Old 10/28/2019, 18:47   #10
 
elite*gold: 100
Join Date: Apr 2008
Posts: 678
Received Thanks: 921
Quote:
Originally Posted by Beni View Post

For some reason, i host this code on 46.101.210.6 port 1337.
If you can msg me with the contents of /chall/flag on this server, i will give you some e*g. Challenged is everyone who deems himself worthy. Please do not speak publicly about potential vulnerabilities/solutions here. PM me if you need any pointers.

[...]

Feel free to ping more people, looking forward to see some skills
This is fun . I really like playing CTF, but I'm not very good at it. The couple of issues I found might already be enough to solve it. At least it's enough to crash it ;D.

@ & @ & @ gogo
florian0 is offline  
Old 10/29/2019, 00:00   #11
 
elite*gold: 14835
The Black Market: 169/0/0
Join Date: Jul 2009
Posts: 3,255
Received Thanks: 780
Quote:
Originally Posted by florian0 View Post
This is fun . I really like playing CTF, but I'm not very good at it. The couple of issues I found might already be enough to solve it. At least it's enough to crash it ;D.

@ & @ & @ gogo
Time to actually learn about some good ol memory corruptions. If not now, when then? One only learns serious **** when he leaves his comfort zone. Gogo

Here is the source you wanna read.

Dont be afraid of malloc and free, once you grasped glibc's memory management one can transfer that knowledge to all other allocators since glibc tend to be the most difficult to understand.

is the general approach known? like which steps to undertake//what to do in order to pop a shell? If necessary, i can provide the binary which is running on the server - but if one compiles it on his own in an up-to-date arch env it should be fine, too. if the approach is unclear, i could provide a general road-map of things to do.

who will be the first to pop a shell?
Beni is offline  
Old 10/29/2019, 01:52   #12
 
elite*gold: 0
Join Date: Feb 2009
Posts: 1,120
Received Thanks: 548
So I've found a solution that would have worked 20 years ago, but not on modern operating systems, so as I don't think it's any solution I'll share it here.
In get_numbers data is allocated using calloc, meaning it will be placed somewhere in the heap. The size is given via a long integer, which on gcc is 64 bit. In the loop to fill this array is iterated by a 32 int bit variable, and can be manually interrupted by giving -1 as input. So when the cnt variable exceeds 2^31-1 (~ 2 billion) it will wrap around (well... actually this is UB but as this is a hacking challange I think we are expected to abuse UB) and begin in the negative range again. Addressing data[i] with a negative i will than access the memory before the data pointer. As the TEXT segment (as well as BSS and DATA, but we don't care about them) lies directly before the heap, and the program doesn't do any other large allocations, we could write directly to the TEXT segment, overriding the assembly. This could than be used to override the whole text segment with a bunch of noops, followed by a shellcode and repeated until a lot of the text segment is filled up. Than the loop will be left, the function will return, and (hopefully) jump into the shellcode (and because most of the code will be noops, chances are high we will jump into a noop and run until we find a shellcode).
This would take at least a day or two (as it would require sending more than 4GB to the stdin of the process) but would work... 20 years ago

But this doesn't work on modern machines because first, the TEXT segment is protected, and would require to first call mprotect, and if I can inject mprotect somewhere, I could also just inject the shellcode already and secondly because nowadays most libc implementations allocate special memory locations (using mmap) for larger memory blocks, meaning that data wouldn't be right after the static segments TEXT, BSS and DATA.
And as you said that you are using a modern libc and linux system, this is off the table. I've found a few more things, which I need to look into if I have a little bit time at hand (sadly I'm currently quite busy so I can't really look into it that much), but I think these are more relevant to the challange so I won't post them here but I just had fun entertaining this idea, even though it's impossible on modern machines
warfley is offline  
Thanks
1 User
Old 10/31/2019, 15:52   #13
 
elite*gold: 14835
The Black Market: 169/0/0
Join Date: Jul 2009
Posts: 3,255
Received Thanks: 780
So,.... given the silence here and the silence (besides some HTTP GET Requests to /chall/flag ) on the server, has everyone given up? In the meanwhile, glibc has had a minor update, the chall is still running with the old version. i can provide you with the libc, ld and the chall binary. just ping me.

Is anyone going to//in the process of developing some exploit for this? has anyone confidence in his findings, that they are indeed exploitable - but lacks the know-how of exploiting them? speak up! . we can talk about approaches/some pointers.

i've expected better results than this. is the prospect of some e*g (might be 13.337e*G, you never know) or (more importantly) _the gain of knowledge_ not incentive enough? :P
Beni is offline  
Old 11/02/2019, 15:26   #14
 
elite*gold: 0
Join Date: Nov 2018
Posts: 333
Received Thanks: 643
I've found an epic exploit: When you enter -1 as the amount of values, calloc is invoked with 0 as first argument. Instead of returning NULL, calloc apparently returns a non-NULL pointer. I have no idea how glibc's memory allocation work, the memory the pointer points to probably contains metadata only. Then we dereference the pointer and write -1 to which I guess is unallocated memory.
sk8land​ is offline  
Old 11/02/2019, 16:27   #15
 
elite*gold: 14835
The Black Market: 169/0/0
Join Date: Jul 2009
Posts: 3,255
Received Thanks: 780
Quote:
Originally Posted by sk8land​ View Post
I've found an epic exploit: When you enter -1 as the amount of values, calloc is invoked with 0 as first argument. Instead of returning NULL, calloc apparently returns a non-NULL pointer. I have no idea how glibc's memory allocation work, the memory the pointer points to probably contains metadata only. Then we dereference the pointer and write -1 to which I guess is unallocated memory.
tl;dr
"epic exploit" or in glibc's terms: intended behaviour.

long version:
malloc has a "minimum allocated size". Due to the metadata and due to more metadata which is being stored once a junk is free'd (next/bck ptr's) a chunk has to have a minimum size to store all that additional data. Here a useful comment within malloc.c:
Quote:
Minimum allocated size: 4-byte ptrs: 16 bytes (including 4 overhead)
8-byte ptrs: 24/32 bytes (including, 4/8 overhead)

When a chunk is freed, 12 (for 4byte ptrs) or 20 (for 8 byte
ptrs but 4 byte size) or 24 (for 8/8) additional bytes are
needed; 4 (8) for a trailing size field and 8 (16) bytes for
free list pointers. Thus, the minimum allocatable size is
16/24/32 bytes.

Even a request for zero bytes (i.e., malloc(0)) returns a
pointer to something of the minimum allocatable size.
and the corresponding code which is the very first thing _int_malloc (the internal malloc implementation, called by malloc, calloc, et al) does:
Code:
  /*
     Convert request size to internal form by adding SIZE_SZ bytes
     overhead plus possibly more to obtain necessary alignment and/or
     to obtain a size of at least MINSIZE, the smallest allocatable
     size. Also, checked_request2size returns false for request sizes
     that are so large that they wrap around zero when padded and
     aligned.
   */

  if (!checked_request2size (bytes, &nb))
    {
      __set_errno (ENOMEM);
      return NULL;
    }
Further, reading the code in the challenge:
Code:
// This is no problem, as we just learned. Access within MINSIZE alloc'd junk.
data[0] = cnt;

// This loop will then terminate immediately, due to the fact that `1 < 0` is false.
// (signed-ness does not play any role here (since 0), so it does not matter if its a jg or ja.) 
for(int i=1; i < cnt + 1; i++){
    [..]
}
thus leaving no room for exploitation, such as OOB writes. (Which might be given, if cnt + 1 results to -1 and the compare is unsigned.)

Anyone else with bug-suggestions? :P


Beni is offline  
Reply


Similar Threads
[Selling] account lvl 30 / average 25000 pi / average 140 rp
01/23/2015 - League of Legends Trading - 0 Replies
Hi everybody i got regularly some fresh lvl 30 account to sell , 20 euros per account . Have a nice day .
charname numbers or guild numbers will take block?
02/21/2010 - Silkroad Online - 6 Replies
charname numbers or guild numbers will take block? some friends said that to me is it right?
Calculating Eudemon checksum
04/04/2008 - EO PServer Hosting - 1 Replies
Hi all, i was wondering if anyone knew what the function is that EO uses to calculate the chksum field in the cq_eudemon table? I tried to find it in the source code, but came up blank. Any help is appreciated :)
Calculating Atack or MAtack
05/04/2007 - CO2 Guides & Templates - 4 Replies
Sometimes you wanted know the atack of an trojan and him dont told you? with thats easy guide, you just need open him equipaments window&#33; "JUST 1 percent error" TROJAN ATACK: The follow instructions is both used to lower and higher atack:
Calculating Hours of Pkp
11/23/2006 - CO2 Guides & Templates - 15 Replies
Ever have a black name or more than 30 pk points? This is how to calculate The total time u will have to wait for those &#39;awful&#39; pk points to get off. 1. Multiply # of pk points by 6. (EX- 100pkp X 6 =600) 2. Divide that number by 60. (EX- 600 / 60) 3. The end number will be the # of hours it will take to get your pkp off.



All times are GMT +1. The time now is 07:45.


Powered by vBulletin®
Copyright ©2000 - 2019, Jelsoft Enterprises Ltd.
SEO by vBSEO ©2011, Crawlability, Inc.

BTC: 33E6kMtxYa7dApCFzrS3Jb7U3NrVvo8nsK
ETH: 0xc6ec801B7563A4376751F33b0573308aDa611E05

Support | Contact Us | FAQ | Advertising | Privacy Policy | Terms of Service | Abuse
Copyright ©2019 elitepvpers All Rights Reserved.