Jonny Jonny - 2 months ago 20
C Question

How can I fix this simple C overflow?

I'm very new to this. I am trying to re-write this code in order to remove the buffer overflow that is picked up in lines 12 + 19.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BUF_SIZE (1024)

int main(int argc, char* argv[]) {
char* inBuf;
char* outBuf;
char* fmt = "the winner is: %s";

inBuf = (char*) malloc(BUF_SIZE);
if (inBuf == NULL) {
return -1;
}
read(0, inBuf, BUF_SIZE);
outBuf = (char*) malloc(BUF_SIZE);
if (outBuf == NULL) {
return -1;
}
sprintf(outBuf, fmt, inBuf);
fprintf(stdout, "%s\n", outBuf);
fprintf(stderr, "%s\n", outBuf);
free(inBuf);
free(outBuf);
}


If someone could provide some insight on the best way to approach this? would be much appreciated thank you.

Answer

Because you use the read function to read user input, you're reading raw bytes as opposed to a string. So what it read in doesn't include a null terminating byte, so you don't have a null terminated string since the buffer returned by malloc is uninitialized.

Use calloc instead of malloc, which returns a buffer initialized to all zeros.

inBuf = calloc(BUF_SIZE, 1);

You should also be checking the return value of read for an error, and you shoudn't cast the return value of malloc/calloc/realloc.

Comments