Page 1 of 2 12 Last
  • Jump to page:
    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2009
    Posts
    6
    Rep Power
    0

    Red face I Can't Fix This C Code! Who Can??


    Greetings.

    Am in dire need of help here. I have been building a certain system which is part of an RPC/PHP extension that creates memory-based matrices for certain data analysis purposes. Am not good in memory management code, I must admit in advance. And hence, am currently stuck in a notorious C's memory miry clay - for sure! All sorts of memory errors and bugs have plagued me for a while now. I need urgent help to finish this application within a few weeks.

    I have recreated, in the following much lesser code (below), to simulate the senario within the other code that seems to be the culprit. After compiling, with Intel C++ Compiler 9.1 or MS Studio 2003, I get the same type of access violation errors of all sorts, including: -
    "The thread 'Win32 Thread' (0x1520) has exited with code 0 (0x0).
    Unhandled exception at 0x7c910ef4 in WIN32ConsoleApp.exe: 0xC0000005: Access violation reading location 0xfffffff8."

    :chomp: Where am I going wrong??? I can't seem to overcome this bug. I have to stick to C - no matter the rugged edges and bleeding corners. SOMEBODY HELP!!!

    Am on XP SP3.

    The code below compiles to a console applic. Run it like this: applic.exe mockpass

    Code:
    /* RECEIVE CONSOLE INPUT AND CREATE A MOCK REPRESENTATION MATRIX */ 
    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>
    #include <ctype.h>
    
    #define EQL == /* Equal To */
    #define NEQL != /* Not Equal To */
    #define LOEQL <= /* Less Than or Equal To */
    #define GOEQL >= /* Greater Than or Equal To */
    
    typedef unsigned int uint;
    typedef signed int sint;
    
    #define e 2.718281828
    #define ROWS 5
    #define COLS 5
    #define MAX_INPUT_LEN 254
    
    void deallocate2D(double **array, int nrows) {
    
    	/*  deallocate each row  */
    	int i;
    	for(i = 0; i < nrows; i++) {
    		free(array[i]);
    		array[i]=NULL;
    	}
    	/*  deallocate array of pointers  */
    	free(array);
    	array=NULL;
    }
    
    void deallocate2C(char **array, int nrows) {
    
    	/*  deallocate each row  */
    	int i;
    	for(i = 0; i < nrows; i++) {
    		free(array[i]);
    		array[i]=NULL;
    	}
    	/*  deallocate array of pointers  */
    	free(array);
    	array=NULL;
    }
    
    void quitapp(uint rowcnt,double **mem2Dblock_a,char **mem2Dblock_b)
    {
    	deallocate2D(mem2Dblock_a,rowcnt);
    	deallocate2C(mem2Dblock_b,rowcnt);
    	fcloseall();
    	fprintf(stderr,"\nCleaned up.\nExiting.\nBye!");
    	exit(0);
    }
    
    void restartapp(char *appexec,uint rowcnt,double **mem2Dblock_a,char **mem2Dblock_b)
    {
    	deallocate2D(mem2Dblock_a,rowcnt);
    	deallocate2C(mem2Dblock_b,rowcnt);
    	fcloseall();
    	system(appexec);
    	exit(0);
    }
    
    int main(int argc,char *argv[])
    { 
    	static uint i=0,j=0,k=0,m=0,n=0,lastknown_rows=0,lastknown_cols=0,lastknown_dims=0,outputlen=0,ramgrowth=0;
    	size_t inputlen;
    	char **kylst=malloc(sizeof(char*)*1);
    	double **kbmtx=malloc(sizeof(double*)*1);
    	char buff[MAX_INPUT_LEN];
    
    	char *dimfilenm = "~dim.tmp";
    	char *kyfilenm = "~ky.lst";
    	char *kbfilenm = "~kb.bin";
    	char *outfilenm = "~out.tmp";
    	FILE *kbfile=NULL;
    	FILE *dimfile=NULL;
    	FILE *kyfile=NULL;
    	FILE *outfile=NULL;
    
    	if(argc==2)
    	{
    		if(((dimfile=fopen(dimfilenm, "r")) NEQL NULL) && (lastknown_dims=fscanf(dimfile,"%d %d",&lastknown_rows,&lastknown_cols))EQL 2)
    		{
    			m=lastknown_rows;
    			n=lastknown_cols;
    			printf("/* Found a valid DIM file showing %dx%d to be the last known dimensions */\n",m,n);
    			printf("/* Locate and try reading the stored KY list file */\n");
    			if((kyfile = fopen(kyfilenm, "r")) EQL NULL) 
    			{ 
    				m=0;
    				n=0;
    				if((kyfile = fopen(kyfilenm, "w")) NEQL NULL) 
    				{ 
    					printf("/* Created a new KY list file */\n");
    					//restartapp(argv[0],m,kbmtx,kylst); 
    					if((kbfile = fopen(kbfilenm, "wb")) NEQL NULL) 
    					{ 
    						printf("/* Created a new KB list file */\n");
    						//restartapp(argv[0],m,kbmtx,kylst); 
    						printf("/* Please restart %s to proceed */\n",argv[0]);
    						fprintf(dimfile,"%d %d\n",m,n);
    						quitapp(m,kbmtx,kylst);
    					}  else {
    						fprintf(stderr, "/* Error creating a new KB list file */\n");
    						quitapp(m,kbmtx,kylst);
    					}
    				}  else { /* if((kyfile = fopen(kyfilenm, "w")) NEQL NULL) */
    					fprintf(stderr, "/* Error creating a new KY list file */\n");
    					quitapp(m,kbmtx,kylst);
    				}				
    				fclose(kbfile);
    			} else { /* if((kyfile = fopen(kyfilenm, "r")) EQL NULL) */
    				if(m>0&&n>0)
    				{
    					m=lastknown_rows;
    					n=lastknown_cols;
    					printf("/* Resize 'char** kylst' to accommodate the last known rows : %d */\n",m);
    					kylst=(char**)realloc(kylst,(size_t)(sizeof(char*)*(m)));
    					if(kylst EQL NULL)quitapp(m,kbmtx,kylst);	
    					k=0;
    					for(i=0;i<(m);i++)
    					{
    						k+=fscanf(kyfile,"%s",buff);
    						if(i > k) {i--; break;}
    						if((kylst[i] = (char *)malloc((size_t)((strlen(buff)+1)*sizeof(char)))) EQL NULL)quitapp(m,kbmtx,kylst);
    						strcpy(kylst[i],buff);
    					}
    					printf("/* Locate and try reading the stored KB data file */\n");
    					if((kbfile = fopen(kbfilenm, "rb")) NEQL NULL) 
    					{ 
    						printf("/* Resize 'double **kbmtx' to accommodate the last known dimensions : %dx%d */\n",m,n);
    						kbmtx=(double**)realloc(kbmtx,sizeof(double*)*m);
    						if(kbmtx==NULL)quitapp(m,kbmtx,kylst);
    						printf("/* Initialize KB with zeros. */\n");
    						for(i = 0; i < m; i++) 
    						{
    							kbmtx[i]=(double*)malloc(sizeof(double)*n);
    							if(kbmtx[i]==NULL) quitapp(m,kbmtx,kylst);
    							for(j = 0; j < n; j++)
    							{
    								kbmtx[i][j]=0.0;
    								printf("%lg\t",kbmtx[i][j]);
    							}
    							printf("\n");		
    						}
    						printf("/* Load the binary file data into KB, row by row. */\n");
    						for (i = 0; i < m; i++) 
    						{
    							if (fread(kbmtx[i], sizeof(double), n, kbfile) != n) 
    							{ 
    								fprintf(stderr, "Error writing to file."); 
    								quitapp(m,kbmtx,kylst);
    							} 
    						}
    
    						printf("/* Close the binary file */\n");
    						fclose(kbfile);
    
    						printf("/* Now print KB to the screen. */\n");
    						for (i = 0; i < m; i++) 
    						{
    							for(j = 0; j < n; j++)
    							{
    								printf("%lg\t",kbmtx[i][j]);
    							}
    							printf("\n");
    						}
    						printf("/* Show KB RAM addresses on the screen. */\n");
    						for (i = 0; i < m; i++) 
    						{
    							for(j = 0; j < n; j++)
    							{
    								printf("%d\t",&kbmtx[i][j]);
    							}
    							printf("\n");
    						}
    					}  else { /* if((kbfile = fopen(kbfilenm, "rb")) NEQL NULL) */
    						fprintf(stderr, "/* Cannot read the KB data file */\n");
    						quitapp(m,kbmtx,kylst);
    					}
    				}
    				fclose(kyfile);
    			}
    			fclose(dimfile);
    			puts("Type A New String and Press <ENTER> To Store in RAM and Binary File, ");
    			for(m=lastknown_rows,n=lastknown_cols;;m++,n++)
    			{
    				if((dimfile = fopen(dimfilenm, "w")) NEQL NULL)
    				{					
    					gets(buff);
    					inputlen=(strlen(buff)+1);
    					if(inputlen<MAX_INPUT_LEN)
    					{
    						if(strcmp(buff,"Q!") EQL 0)
    						{
    							quitapp(m,kbmtx,kylst);
    						}
    						if((kyfile = fopen(kyfilenm, "a")) NEQL NULL)
    						{
    							kylst=(char**)realloc(kylst,(size_t)(sizeof(char*)*(m+1)));
    							if(kylst EQL NULL)quitapp(m,kbmtx,kylst);
    							kylst[m]=(char*)malloc((size_t)(sizeof(char)*inputlen));
    							if(kylst[m] EQL NULL)quitapp(m,kbmtx,kylst);
    							strcpy(kylst[m],buff);
    							if((kbmtx=(double **)realloc(kbmtx,(size_t)((m+1)*sizeof(double*)))) NEQL NULL)
    							{
    								if((kbmtx[m]=(double *)malloc((size_t)((n+1)*sizeof(double)))) EQL NULL)quitapp(m,kbmtx,kylst);
    								for(i=0;i<(m+1);i++)
    								{
    									for(j=0;j<(n+1);j++)
    									{
    										kbmtx[i][j]=0.0;
    									}
    								}
    							} else quitapp(m,kbmtx,kylst);
    							printf("Committing to KY list file\n");
    							fprintf(kyfile,"%s\n",kylst[m]);
    							printf("/* Opening the KB binary data file for writing */\n");
    							if((kbfile = fopen(kbfilenm, "wb")) NEQL NULL) 
    							{ 
    								for(i=0;i<(m+1);i++)
    								{
    									if((fwrite(kbmtx[i],sizeof(double),(n+1),kbfile))!=(n+1))quitapp(m,kbmtx,kylst);
    								}	
    								fclose(kbfile);
    							} else {
    								fprintf(stderr, "Error opening KB file for updates."); 
    								quitapp(m,kbmtx,kylst); 
    							}						
    							fclose(kyfile);
    							fprintf(dimfile,"%d %d\n",m+1,n+1);
    							//lastknown_dims=flushall();					
    							//printf("/* Written %d updates to DIM file */\n",lastknown_dims);							
    							printf("/* Show KB RAM addresses on the screen. */\n");
    							for (i = 0; i < (m+1); i++) 
    							{
    								for(j = 0; j < (n+1); j++)
    								{
    									printf("%lg\t",kbmtx[i][j]);
    								}
    								printf("\n");
    							}
    							puts("Type and Store Another String Or Type Q! and <ENTER> To Quit: ");
    						} else printf("/* Oops! Cannot open KY list file for updates */\n");
    					} else { /* if(buff<MAX_INPUT_LEN) */
    						printf("/* Oops! Your input is too large. Keep it below 254 characters */\n");
    					}						
    				}  else printf("/* Oops! Cannot open DIM file for updates */\n");
    				fclose(dimfile);
    			}
    		} else { /* if(((dimfile=fopen(dimfilenm, "r+")) NEQL NULL) && (lastknown_dims=fscanf(dimfile,"%d %d",&lastknown_rows,&lastknown_cols))EQL 2) */
    			fprintf(stderr, "/* Cannot read or verify integrity of the DIM file */\n");
    			if((dimfile = fopen(dimfilenm, "w")) NEQL NULL) 
    			{ 
    				printf("/* Created a new DIM file */\n"); 
    				fprintf(dimfile,"%d %d\n",0,0);
    				printf("/* Please restart %s to proceed */\n",argv[0]);
    				quitapp(m,kbmtx,kylst);
    			}  else {
    				fprintf(stderr, "/* Error creating a new DIM file */\n");
    				quitapp(m,kbmtx,kylst);
    			}
    		}
    		quitapp(m,kbmtx,kylst);
    	}
    
    	return(0); 
    }
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Loyal (3000 - 3499 posts)

    Join Date
    May 2004
    Posts
    3,417
    Rep Power
    887
    If you want help with non-trivial code, post code that compiles. You apparently left out some include files.
    I no longer wish to be associated with this site.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Loyal (3000 - 3499 posts)

    Join Date
    May 2004
    Posts
    3,417
    Rep Power
    887
    Cleaning it up results in the following run-time output:

    /* Cannot read or verify integrity of the DIM file */
    /* Created a new DIM file */
    /* Please restart app to proceed */


    Have you got some example files to work with?
    I no longer wish to be associated with this site.
  6. #4
  7. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,396
    Rep Power
    1871
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2009
    Posts
    6
    Rep Power
    0

    Unhappy The Files Are Only Mock Files - Malloc/Realloc/Free Behaviour Is The Real Issue


    Originally Posted by jwdonahue
    Cleaning it up results in the following run-time output:

    /* Cannot read or verify integrity of the DIM file */
    /* Created a new DIM file */
    /* Please restart app to proceed */


    Have you got some example files to work with?
    Thanks Jwdonahue for your earlier remarks, am encouraged at least.

    There really are no useful files to work with, bcoz the applic when run the first time should create new files, which should again be deleted to return the applic to blank again, (remember, they'r just mock files).

    The main issue here is this memory bug :confused: , file management is ok on the live application. This application is just for prove of concept here, the real code is part of a much larger code base that would be practically impossible to submit for any reasonable and timely assistance.

    Thanks for continued help.
  10. #6
  11. No Profile Picture
    Contributing User
    Devshed Loyal (3000 - 3499 posts)

    Join Date
    May 2004
    Posts
    3,417
    Rep Power
    887
    So you still haven't tied it down yet?
    I no longer wish to be associated with this site.
  12. #7
  13. No Profile Picture
    Contributing User
    Devshed Loyal (3000 - 3499 posts)

    Join Date
    May 2004
    Posts
    3,417
    Rep Power
    887
    Hmm... so I went back and copied your entire posted program and compiled it. NEQ? Yuck! If you don't like C or C++ find another language. Anyway, you apparently haven't told us all the steps to repro the bug because I just don't hit.

    Comments on this post

    • clifford agrees : Yes because GOEQL is so much more readable and east to type than >= ! ;-)
    I no longer wish to be associated with this site.
  14. #8
  15. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2009
    Posts
    6
    Rep Power
    0

    Unhappy Did I Get You Right?


    Originally Posted by jwdonahue
    If you want help with non-trivial code, post code that compiles. You apparently left out some include files.
    Jwdonahue, did I fully understand your request?!

    All the includes here are very much standard C headers for sure!

    See...
    Code:
    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>
    #include <ctype.h>
    About paying, er..., well... how about proving the fix by returning a sound exec which when I test and find working we can discuss paying for the source code? After all the application really does nothing sensible, even if it ran without any bug. It is the concept proven, and therefore the application of the concept in the other code, that means everything. :confused:
  16. #9
  17. No Profile Picture
    Contributing User
    Devshed Loyal (3000 - 3499 posts)

    Join Date
    May 2004
    Posts
    3,417
    Rep Power
    887
    Deal! You're gonna owe me a beer ;).
    I no longer wish to be associated with this site.
  18. #10
  19. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2009
    Posts
    6
    Rep Power
    0

    Unhappy How To Launch The Bug


    Originally Posted by jwdonahue
    Hmm... so I went back and copied your entire posted program and compiled it. NEQ? Yuck! If you don't like C or C++ find another language. Anyway, you apparently haven't told us all the steps to repro the bug because I just don't hit.
    Can't see the bug??

    Try this:-
    1. Compile the C code to some console exectutable.
    2. Launch a command prompt pointing to the executable.
    3. Make sure any previous output files by the applic are deleted i.e. ~ky.lst,~kb.bin and ~dim.tmp
    4. Call the executable with one argument e.g. myexec.exe arg1
    5. Rerun the exec file as instructed by the runtime output, as it creates the necessary data files (i.e. ~ky.lst,~kb.bin and ~dim.tmp)
    6. You will eventually enter into a sort of console input mode that will allow you to start typing/storing char strings with the return key.
    7. Repeat typing/return sequence for about 3 or 4 times. The bug should happen!

    No Sir, I don't wanna switch from C for this code. It should work right or there MUST be a plausible reason why it can't :chomp: . Furthermore the real code base in C and I can't go about at this stage to even imagine leaving C/C++ for whatever else.
  20. #11
  21. No Profile Picture
    Contributing User
    Devshed Loyal (3000 - 3499 posts)

    Join Date
    May 2004
    Posts
    3,417
    Rep Power
    887
    Achieved a repro with:

    testApp mockpass < testinput.txt

    where testinput.txt is:

    String1
    x
    String2
    y
    String3
    z


    Error is a debug assertion at line 785 of dbgheap.c, expression: _CrtIsValidHeapPointer(pUserData)

    Is that what you need fixed? We have to be clear here because this application is a sphincter trying to crap on everything that comes near it and without any clue what the application is supposed to do, it's hard to fix all those problems.
    I no longer wish to be associated with this site.
  22. #12
  23. No Profile Picture
    Contributing User
    Devshed Loyal (3000 - 3499 posts)

    Join Date
    May 2004
    Posts
    3,417
    Rep Power
    887
    You definitely need to talk your coders about their style. How many of them had pink shirts on today?
    I no longer wish to be associated with this site.
  24. #13
  25. Contributing User

    Join Date
    Aug 2003
    Location
    UK
    Posts
    5,114
    Rep Power
    1803
    Originally Posted by deendee
    No Sir, I don't wanna switch from C for this code.
    You seem to have missed the point of JD's comment. He was referring to the ridiculous definition of comparison operator macros as an apparent attempt to redefine your own language.

    The really bizarre thing is that having defined them you have used them in some places but not others. In a language where macros for perhaps anything other than literal constants are generally considered a 'bad thing'(tm), those are amongst the most pointless and insidious examples of abuse. The whole semantics of your program can be changed by changing the definitions of those macros, and you might be debugging the code for a long time before you noticed the cause.

    It is just barely acceptable to define such macros if you happen to be using a keyboard without the necessary symbols (if there is such a thing), but I would imagine that anyone doing a significant amount of C code in a region with such a keyboard would just get a US or UK keyboard specifically for that purpose.

    Clifford.

    Comments on this post

    • jwdonahue agrees : Exactly. If you prefer EQU to "==" then there are more suitable languages out there.
    Last edited by clifford; July 2nd, 2009 at 03:10 AM.
  26. #14
  27. No Profile Picture
    Contributing User
    Devshed Loyal (3000 - 3499 posts)

    Join Date
    May 2004
    Posts
    3,417
    Rep Power
    887
    Please tell me the person who wrote this has been fired:

    Code:
    	char **kylst= (char**)malloc(sizeof(char*)*1);
    	double **kbmtx= (double**)malloc(sizeof(double*)*1);
    I no longer wish to be associated with this site.
  28. #15
  29. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2009
    Posts
    6
    Rep Power
    0

    Angry Yes JD, Fired


    Originally Posted by jwdonahue
    Please tell me the person who wrote this has been fired:

    Code:
    	char **kylst= (char**)malloc(sizeof(char*)*1);
    	double **kbmtx= (double**)malloc(sizeof(double*)*1);
    I've just fired him! :mad:

    Correction...
    Code:
    char **kylst=malloc(sizeof(char*)*1);
    double **kbmtx=malloc(sizeof(double*)*1);
Page 1 of 2 12 Last
  • Jump to page:

IMN logo majestic logo threadwatch logo seochat tools logo