Skip site navigation (1)Skip section navigation (2)
Date:      Mon, 21 Oct 2002 10:59:26 -0700
From:      Terry Lambert <tlambert2@mindspring.com>
To:        Danny Braniss <danny@cs.huji.ac.il>
Cc:        freebsd-hackers@FreeBSD.ORG
Subject:   Re: malloc
Message-ID:  <3DB4407E.A9F06218@mindspring.com>
References:  <E183Yoh-0009TR-00@cse.cs.huji.ac.il>

next in thread | previous in thread | raw e-mail | index | archive | help
Danny Braniss wrote:
> the attached program - which shows the 'efficiancy' of our scientific
> programmers - tickled my curiosity.
[ ... ]
> comments?

Your code is not efficient; try this instead:

> #include <stdlib.h>
> #include <sys/time.h>
> #include <stdio.h>
> 
> int MAX_N, mem;
> 
> int main(int argc , char ** argv){
>      int        i;
>      int        ** arr;
	int	*space;
>      struct timeval t1, t2;
> 
>      if(argc > 1)
>           MAX_N = atoi(argv[1]);
>      else
>           MAX_N = 100000000;
> 
>      gettimeofday(&t1, 0);
>      mem = sizeof (int *) * MAX_N;
>      arr = malloc(mem);
>      if(arr == NULL) {
>           perror("Malloc");
>           exit(1);
>      }
	space = malloc(sizeof(int)* MAX_N);
	if(space == NULL) {
		perror("malloc2");
		printf("failed to allocate array space\n");
		exit(1);
	}
	for (i = 0 ; i < MAX_N ; ++i ){
		arr[i]  = &space[ i];
		*arr[i] = i;
	}
>      gettimeofday(&t2, 0);
>      printf ("%s took %f seconds, mem used=%d(%dM)\n",
>              getenv ("HOST"),
>              t2.tv_sec-t1.tv_sec + (t2.tv_usec-t1.tv_usec)/(float)(1000000),
>              mem, mem / (1024 * 1024));
> 
>      for (i = 0 ; i < MAX_N ; ++i ){
>           if(*arr[i] != i)
>                printf("GUEVALT! %d] %d\n", i, *arr[i]);
>      }
>      exit(0);
> }

The reason it crashes under FreeBSD is that you are allocating more
memory than you have swap + RAM for, but not more memory than you have
available address space for; see also "man malloc", and see if you
have debugging options turned on.

Note that there is no "magic flag" to turn overcommit into spelicit
commit on memory allocation (maybe "J" would qualify, since it forces
initialization).

The normal way you would do this is to write your own allocator that
allocated in page-sized chunks, touched each page, and had a fault
signal handler, and backing off, OR setting the 'memoryuse' and
'datasize' limits before tunning the process ("man limit" and also
"man login.conf").

-- Terry

To Unsubscribe: send mail to majordomo@FreeBSD.org
with "unsubscribe freebsd-hackers" in the body of the message




Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?3DB4407E.A9F06218>