Clearing a char pointer

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • KiddoGuy
    New Member
    • Nov 2008
    • 17

    Clearing a char pointer

    I have the following code
    Code:
    int parseFile(FILE* fp, char s[]) {
    	char *buffer;
    	int c, i;
    	
    	i = 0;
    	buffer = (char*)malloc(MAX_ARRAY+1);
    	while ((c = getc(fp)) != EOF) {
    		while (!isspace(c)) {
    			*(buffer+i) = c;
    			i++;
    			c = getc(fp);
    		}
    		i = 0;
    		if (strcmp(buffer, s) == 0) {
    			return 0; /* found */
    		}
    	}
    	return 1; /* not found */
    }
    and the problem is when I run it, each time through the loop it will still retain what was left over if the previous loop had more chars. I want to blank out this pointer each time through the loop so I will get clean results. I thought using free() would help, but it did nothing.
  • arnaudk
    Contributor
    • Sep 2007
    • 425

    #2
    You have to initialize your buffer. You allocated memory for it alright but that memory can contain any junk, including what happened to be there before. free() releases the memory but doesn't wipe the buffer either.

    You can initialize your buffer, setting all bits to zero, by using calloc() instead of malloc(). Either use that together with free() to reallocate a clean buffer each time, or just overwrite the buffer's contents with zeros.

    Comment

    • vmpstr
      New Member
      • Nov 2008
      • 63

      #3
      In C, a string is a collection of characters that ends with 0 (or '\0' if you prefer).

      So when reading character by character, and filling in the buffer, you want to ensure that the next character is '\0'.

      something along the lines.

      *(buffer + i) = c;
      *(buffer + i + 1) = 0;

      and conveniently, this is sort of equivalent to clearing it all out with 0s.

      Comment

      Working...