malloc - Trouble using free() in C -


i having trouble free. want allocate 2d array of *chars , free them, fails @ runtime. learning pointers , on complicating this.

  //numberoflines, numberofdie, , widthofdie ints (3, 2, 3),   int ilinesize, iline, idie;   char **pidiestring;    pidiestring = (char**)malloc(numberoflines * sizeof(*pidiestring)); //allocate number of lines   ilinesize = numberofdie * widthofdie * sizeof(char); //size of line   for(iline = 0; iline < numberoflines; iline++)   {      pidiestring[iline] = (char*)malloc(ilinesize); //allocate size of lines   }    //stuff happens    /*freeing*/   for(iline = 0; iline < numberoflines; iline++)      {      free(pidiestring[iline]);      }   free(pidiestring); 

i believe there wrong in //stuff happens .

added prints verify if memory getting allocated , freed follows:

#include <stdio.h> #define numberoflines 3 #define numberofdie 2 #define widthofdie 3 int main(void) {    int ilinesize, iline, idie;   char **pidiestring;    pidiestring = (char**)malloc(numberoflines * sizeof(*pidiestring)); //allocate number of lines   printf("allocated pidiestring: 0x%x\n",pidiestring );   ilinesize = numberofdie * widthofdie * sizeof(char); //size of line    for(iline = 0; iline < numberoflines; iline++)   {      pidiestring[iline] = (char*)malloc(ilinesize); //allocate size of lines      printf("allocating pidiestring[%d]: 0x%x\n",iline,pidiestring[iline] );   }    //stuff happens    /*freeing*/   for(iline = 0; iline < numberoflines; iline++)   {      printf("freeing pidiestring[%d]: 0x%x\n",iline,pidiestring[iline] );      free(pidiestring[iline]);   }    printf("\nfreeing pidiestring: 0x%x\n",pidiestring );   free(pidiestring);   return 0; } 

the output seems fine.

allocated pidiestring: 0x966e008 allocating pidiestring[0]: 0x966e018 allocating pidiestring[1]: 0x966e028 allocating pidiestring[2]: 0x966e038 freeing pidiestring[0]: 0x966e018 freeing pidiestring[1]: 0x966e028 freeing pidiestring[2]: 0x966e038  freeing pidiestring: 0x966e008 

elaborate on "but fails @ runtime"...as in see crash ? if yes check //stuff happens inavlid memory access...


Comments

Popular posts from this blog

user interface - How to replace the Python logo in a Tkinter-based Python GUI app? -

objective c - Greedy NSProgressIndicator Allocation -

how to set an OCR language in Google Drive -