Thread: unable to free string

  1. #1
    Registered User
    Join Date
    Feb 2005
    Posts
    61

    unable to free string

    When trying to execute this piece of code, the program craches when it reaches free(zin). When I remove the free(zin), everything works well, but I think it's better to free the allocated memory. Does anyone know what I'm doing wrong ?

    Code:
    void readFile(){
    	FILE *f;
    	char *zin, *tag;
    
    	if ( !(f = fopen("test.txt", "r")) ) return;
    
    	zin = malloc(sizeof(char));
    	while (fgets(zin, SKY_MAX_ZIN_SIZE, f) != NULL){
    		tag = fileZoekTag (zin);
    		fileProcessTag(tag);
    	}
    	free (zin);
    	fclose(f);
    }

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Code:
    zin = malloc(sizeof(char));
    Did you intend to allocate more than one byte? If SKY_MAX_ZIN_SIZE is bigger than 1, you are lying to fgets. So the loop will either write beyond memory you can write to, or the loop will never go anywhere.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    Registered User
    Join Date
    Feb 2005
    Posts
    61
    That was the problem indeed. Thanks.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C++ ini file reader problems
    By guitarist809 in forum C++ Programming
    Replies: 7
    Last Post: 09-04-2008, 06:02 AM
  2. Please check my C++
    By csonx_p in forum C++ Programming
    Replies: 263
    Last Post: 07-24-2008, 09:20 AM
  3. Inheritance Hierarchy for a Package class
    By twickre in forum C++ Programming
    Replies: 7
    Last Post: 12-08-2007, 04:13 PM
  4. Classes inheretance problem...
    By NANO in forum C++ Programming
    Replies: 12
    Last Post: 12-09-2002, 03:23 PM
  5. creating class, and linking files
    By JCK in forum C++ Programming
    Replies: 12
    Last Post: 12-08-2002, 02:45 PM