Saturday, December 16, 2017

Day 20 (contd) - Dynamic Memory Allocation

CLASSWORK:
/* */
/* This program determines the maximum contiguous */
/* memory allocation that can be reserved during a */
/* specific program execution. */
#include <stdio.h>
#include <stdlib.h>
#define UNIT 1000000
int main(void)
{
/* Declare and initialize variables. */
double k=1;
int *ptr;
/* Find maximum amount of contiguous memory */
/* available in units of millions of integers. */
ptr = (int *)malloc(UNIT*sizeof(int));
while (ptr != NULL)
{
printf("%f integers \n",(k)*UNIT);
free(ptr);
k++;
ptr = (int *)malloc(k*UNIT*sizeof(int));
}
/* Print maximum amount of memory available. */
printf("Maximum contiguous memory available: \n");
/* Exit program. */
return 0;
}

HOMEWORK:
/* */ 
/* This program reads a seismic data file and then */ 
/* determines the times of possible seismic events. */ 
/* Dynamic memory allocation is used. */ 
#include <stdio.h>
#define FILENAME "seismic1.txt" 
#define THRESHOLD 1.5 
int main(void) 
{ /* Declare variables and function prototypes. */ 
int k, npts, short_window, long_window; 
double *sensor, time_incr, short_power, long_power, ratio; 
FILE *file_ptr; 
double power_w(double *ptr,int n); 
/* Read data header and allocate memory. */ 
file_ptr = fopen(FILENAME,"r"); 
if (file_ptr == NULL) 
printf("Error opening input file. \n"); 
else { fscanf(file_ptr,"%d %lf",&npts,&time_incr); 
sensor = (double *)malloc(npts*sizeof(double)); 
if (sensor == NULL) 
printf("Not enough memory available. \n"); 
else (no changes in the remainder of the program)


No comments:

Post a Comment