-2

I came across this question in C programming:

Question: what is the flaw in the code snippet below that fills a buffer with zeros? How can the problem be fixed?

char*buf;
buf=malloc(BUFSIZ);
memset(buf,0,BUFSIZ);

I have tried to find the flaw, but everything works fine for me. Please let me know if there is any flaw in the above C program.

manlio
  • 18,345
  • 14
  • 76
  • 126

2 Answers2

1
//somewhere
const size_t BUFSIZE = 1000; //or it could be 0!
...
char *buf = NULL;
if (BUFSIZE > 0) {
    buf = (char*) malloc(BUFSIZ); //cast is not necessary on most compilers

    if (buf == NULL) {
        //some error processing
    } else {
        memset(buf, 0, BUFSIZ);
    }

    free(buf);
    buf = NULL;
}
  1. set pointer to NULL
  2. malloc positive number of bytes, because behaviour for 0 is implementation-specific
  3. check it is not null after malloc
  4. free memory. If it is NULL nothing happens
  5. nullify pointer after free
  6. cast malloc, some compilers will warn, not an error. Well, really, do not cast
  7. maybe there are some standards like MISRA, so this code is absolutely invalid for that standard
  8. and also this can be thread-unsafe
Ivan Ivanov
  • 2,076
  • 16
  • 33
0

First thing is that malloc returns a pointer of type 'void' so better to typecast it to (char *). Second thing "malloc" can fail, in that condition it will return "NULL" pointer, check for this condition. I am sure BUFSIZ is defined in code somewhere!

Kapil
  • 31
  • 2
  • 2
    About your first point : It's not a good habit to cast malloc return values in C : http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – Logar Sep 12 '14 at 08:38