I159
I159

Reputation: 31109

Memory management with `fgets`

I want to master memory management in C. I have started to use Valgrind. And this is my first memory problem which I'm solving.

Significant variables:

#define BUF_SIZE 1024
char buffer[BUFSIZ]; 
char *parsed;        

This is tokenizer:

char **tokenize(char *buffer) {                                              
  parsed = malloc(sizeof(buffer)); // #286                                           
  tokens = (char**)malloc(sizeof(buffer));                                   
  if (buffer[0] == '\n'){                                                    
    printf("What do you expect? Enter sumething!\n");                        
    exit(0);                                                                 
  }                                                                          
  strcpy(parsed, buffer); // #292
  free(buffer);                                                              
  for (i=0; i < 2; i++){                                                     
    if (!(((tok = strsep(&parsed, delimeter)) != NULL) && (tokens[i] = tok)))
      exit(0);                                                               
  }                                                                          
  return tokens;                                                             
}        

Tokenizer usage:

while (fgets(buffer, BUFSIZ, stdin)) {
  tokens = tokenize(buffer); // #303

Valgrind traceback:

Invalid write of size 1
   at 0x4C2BFFC: strcpy (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
   by 0x4014BF: tokenize (B_tree.c:292)
   by 0x40156B: main (B_tree.c:303)
Address 0x51f2048 is 0 bytes after a block of size 8 alloc'd
   at 0x4C2B6CD: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
   by 0x401472: tokenize (B_tree.c:286)
   by 0x40156B: main (B_tree.c:303)

Significant lines have comments with original line numbers, used in the traceback.

The buffer is definitely bigger than a value which passed into it. What is the common problem there? How to solve it?

Upvotes: 0

Views: 569

Answers (1)

user3386109
user3386109

Reputation: 34829

You've got two variables called buffer. One is a global variable buffer[BUFSIZ]. The other is the function parameter char *buffer. Note that the function parameter takes precedence over the global variable, so sizeof(buffer) is the sizeof(char *).

Upvotes: 1

Related Questions