Solved

Another problem with malloc

Posted on 1997-03-10
1
423 Views
Last Modified: 2012-08-13
I thought that I understood malloc, however, the following program aborts and I dont know why



#include <stdio.h>
#include <string.h>
#include <stdlib.h>


#include "uleis_rate.h"
#include "df.h"
#include "mfhdf.h"
#define STEP 100
#define NROWS 100
#define NCOLUMNS 2
#define MAXLINE 80
#define MAX_NAME 11
int decompress8(int);
int decompress16(int);
void get_set(int *tstart, int *tstop, int *type, int *channel, int *sector);
int call_file(int *type, int *ii, int *jj, int *sec, int *cn, int *time);
int control_file(FILE *filename);
int geti(char *);
void main(argc, argv)
int argc;
char *argv[];
{
  int32 hdf_fp,sd_id;
  struct URateSet ratetestdata;
  int ii,jj,kk,cc,dd,zz,retval,flag;
  int time, temp, temp_time;
  int bits, tstart, tstop, sector, channel;
  int rate_type,value;
  int **arr1;
  int number = 0, loop = 0, nrows = NROWS;
  int i,j;
  char ofile[MAXLINE], ctrl_buf[MAXLINE];
  char *ofile_ptr;
  char tempbuf[MAXLINE], *temp_ptr;
  char hold[MAXLINE], *hold_ptr;
  char *namebuf, *name_ptr;
  char firstbuf[MAX_NAME], *first_ptr;
  char *comma_ptr;
  int difference, newline=0;
  FILE       *ofp, *ctrl_ptr;




  if (argc > 3){
      printf("Usage: rd_hdf hdf_file control_file\n");
      exit(1);
    }
  /* open hdf input file */

  puts(" Opening HDF file .");
  if ((hdf_fp=Hopen(argv[1], DFACC_READ, 0))==FAIL){
      fprintf(stderr, "Hopen: could not open hdf file\n");
      HEprint(stdout, 0);
      exit(-1);
    }
  puts(" Starting HDF file ..");
  Vstart(hdf_fp);
  printf(" %u %s %d\n", argv[1], argv[1], argv[1]);
  if ((sd_id=SDstart(argv[1], DFACC_RDONLY))==FAIL){
      fprintf(stderr, "SDstart: could not open hdf file\n");
      exit(-1);
    }

  /* opening control file */
  printf(" value of argc is %d\n", argc);
  if (argc == 2){
    printf(" No control file entered\n");
  }else{
    puts(" A control file was entered");
    if((ctrl_ptr = fopen(argv[2], "r")) == NULL){
      puts(" Error opening control file");
      return;
    }
  }

  puts(" enter output file ");
  gets(ofile);

   if ((ofp = fopen(ofile, "w")) == NULL)
      {puts(" Error opening output file");
       return;
      }      

  puts(" before control file input");
  i = control_file(ctrl_ptr);
  if(i == -1)
    puts(" big time error in control_file reading");
  puts(" after control file input");


   arr1 = (int **)malloc (NROWS * sizeof (int *));
   puts(" after NROWS malloc");
   for (i=0; i< NROWS; i++){
     printf(" malloc'ing row # %d\n", i);
     arr1[i] = (int *)malloc (NCOLUMNS * sizeof (int));
   }

   puts(" after initial malloc");
  init_rd_uleis_rate(hdf_fp, sd_id);
  puts(" after initialization of hdf file ");
 
  get_set(&tstart, &tstop, &rate_type, &channel, &sector);

  fprintf(ofp,"%10s %10s %10s %10s\n", "time", "sector", "channel", "number");

   printf(" arr1 = %u\n", arr1);

  for (ii=tstart; ii<tstop; ii++){
    for (jj=0; jj<10; jj++){
      value = call_file(&rate_type, &ii, &jj, &sector, &channel, &time);
      if (loop <  100){
        arr1[number][0] = time;
        arr1[number][1] = value;
        loop++;
      }
      else {
        loop = 0;
        nrows += NROWS;
        printf("Dynamically allocating %u to size %d\n",arr1, nrows);
        arr1 = (int **)realloc (arr1, nrows * sizeof (int *));
        for (i=0; i<nrows-NROWS; i++)
          arr1[i] = (int *)realloc(arr1[i], NCOLUMNS * sizeof (int));
        for (i=nrows-NROWS;i<nrows;i++)
          arr1[i] = (int *)malloc(NCOLUMNS * sizeof (int));
        arr1[number][0] = time;
        arr1[number][1] = value;
        loop++;
      }
      number++;
    }
  }
  for (i=0;i<number;i++)
    fprintf(ofp, "%10d %10d %10d %10d\n", arr1[i][0], sector,
            channel, arr1[i][1] );



  /* all done, close HDF file */

  close_rd_uleis_rate();
  fprintf(stdout,"\nVS detached \n");
  Vend(hdf_fp);
  fprintf(stderr,"VS ended \n");
  if (Hclose(hdf_fp)==FAIL){
      fprintf(stderr, "Hclose: could not close hdf file\n");
      exit(-1);
  }
  fprintf(stderr,"file closed \n");
  if(fclose(ofp) != 0)
      {puts(" error closing output file");
      }  
  if(fclose(ctrl_ptr) != 0)
      {puts(" error closing control file");
      }  

  exit(0);
}


The output from the program is as follows:

urate_rd uleis.hdf first.ctrl
 Opening HDF file .
 Starting HDF file ..
 4026530629 uleis.hdf -268436667
 value of argc is 3
 A control file was entered
 enter output file
out.txt
 before control file input
# lines beginning with a # are comment lines
 
#       another comment line
 
 
 
CHANNEL, 2,8,3,2,0,
 
 inside channel CHANNEL
 inside channel 2
 inside channel 8
 inside channel 3
 inside channel 2
 inside channel 0
 
 
OUTPUT_FILE, out.txt,
 
 inside output_file OUTPUT_FILE
 inside output_file out.txt
 
 
HAPPY, dummy,    really dum,   garbage,
 inside happy HAPPY
 inside happy dummy
 inside happy really dum
 inside happy garbage
 after control file input
 after NROWS malloc
 malloc'ing row # 0
 malloc'ing row # 1
 malloc'ing row # 2
Bus error (core dumped)




Any advise on why this is aborting, how to fix it, and any help on whether this is the best way to use malloc for two dimensional/three dimensional arrays would be very helpfull

Thanks Dennis
0
Comment
Question by:haggedk1
1 Comment
 
LVL 5

Accepted Solution

by:
julio011597 earned 100 total points
Comment Utility
It seems you are going the right way, tough it's not possible to debug your code because of the external calls.

Just a few points:

Do NOT cast malloc(), since this way, in case of error, you are possibly fooling your compiler; and ALWAYS check the return value of malloc().
So your code should look like this:

if(!(arr1 = malloc (NROWS * sizeof(int *)))) {
  /* check errno and exit
     'cause malloc() failed! */
}
puts(" after NROWS malloc");
for (i=0; i< NROWS; i++){
  if(!(arr1[i] = (int *)malloc(NCOLUMNS * sizeof(int)))) {
    /* malloc() failed */
  }
  printf(" malloc'ed row # %d\n", i);
}

Ditto for realloc().

BTW, your code looks very odd while reallocating; i.e. you don't need to realloc the previously allocated columns: just realloc() the rows and malloc() the _new_ cols:

/* add error checking!! */
loop = 0;
nrows += NROWS;
printf("Dynamically allocating %u to size %d\n",arr1, nrows);
arr1 = realloc(arr1, nrows * sizeof(int *));
for (i=nrows-NROWS;i<nrows;i++)
  arr1[i] = malloc(NCOLUMNS * sizeof(int));
arr1[number][0] = time;
arr1[number][1] = value;
loop++;

Last note (and least):
you could avoid using the 'loop' variable and the first bunch of malloc's, modifying the if statement as this:

int **arr1 = NULL;

...

if(number % NROWS) {
  ...
} else {
  ... realloc() and malloc() stuff here ...
}
number++;

because a realloc performs a malloc when given a null pointer.

All of this said, my only advise to fix a bus error is: always check return values of *alloc calls, while debugging check your pointers here and there (i.e. put some printf("a_pointer: %p\n", a_pointer);), check and check...

HTH, julio
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Why does my while loop in C run indefinitely? 10 89
Test against App 49 128
why "." vs "->" 23 115
C Language combined operators 28 101
Have you thought about creating an iPhone application (app), but didn't even know where to get started? Here's how: ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ Important pre-programming comments: I’ve never tri…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
The goal of this video is to provide viewers with basic examples to understand and use structures in the C programming language.
The goal of this video is to provide viewers with basic examples to understand opening and writing to files in the C programming language.

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now