0

So I'm reading from a file into a buffer. By default, this method doesn't null terminate my string.

size_t result;
size_t total = 0;

/* Get the file size */
FILE* pfile; 
pfile = fopen(filename, "rb");
fseek(pfile, 0, SEEK_END);
long lfile = ftell(pfile);
rewind(pfile);

char* file_buffer = malloc(sizeof(char) * lfile);
while ((result = fread(file_buffer, 1, lfile, pfile)) > 0)
{
    total += result; 
}

resp->content_length = lfile;
file_buffer[lfile] = '\0'; //so I try to null terminate it here. 

But I'm getting invalid write of size 1. What am I doing wrong?

Is there another way to null terminate what's in my buffer?

1
  • 1
    What do you mean by invalid write? BTW, you are allocating size lfile and you are trying to access a position outside it file_buffer[lfile] = '\0'. Commented Dec 4, 2013 at 22:41

2 Answers 2

4

Your computation of the string length seems to be wrong in the call to malloc. You have to add 1 to account for the 0 character.

Edit: BTW, your use of sizeof(char) is ... useless. sizeof and malloc are just defined that they count things in the size of a char, so sizeof(char) will always be 1.

Sign up to request clarification or add additional context in comments.

Comments

1

file_buffer[lfile] is out of bounds, since file_buffer only has lfile elements. It's like saying int x[1]; x[1] = 0;.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.