• C

Another problem with malloc

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");
  /* 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);
  puts(" Starting HDF file ..");
  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");

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

  puts(" enter output file ");

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

  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;
      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;
  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 */

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


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
 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
Who is Participating?
julio011597Connect With a Mentor Commented:
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;

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 ...

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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.