By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
458,135 Members | 1,280 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 458,135 IT Pros & Developers. It's quick & easy.

Clearing a char pointer

P: 17
I have the following code
Expand|Select|Wrap|Line Numbers
  1. int parseFile(FILE* fp, char s[]) {
  2.     char *buffer;
  3.     int c, i;
  5.     i = 0;
  6.     buffer = (char*)malloc(MAX_ARRAY+1);
  7.     while ((c = getc(fp)) != EOF) {
  8.         while (!isspace(c)) {
  9.             *(buffer+i) = c;
  10.             i++;
  11.             c = getc(fp);
  12.         }
  13.         i = 0;
  14.         if (strcmp(buffer, s) == 0) {
  15.             return 0; /* found */
  16.         }
  17.     }
  18.     return 1; /* not found */
  19. }
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.
Nov 17 '08 #1
Share this Question
Share on Google+
2 Replies

P: 424
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.
Nov 17 '08 #2

P: 63
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.
Nov 18 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.