• Wed. Dec 7th, 2022


Latest Software News and Hacks

Writing data to a pointed to buffer: incorrect behavior when overwriting


Sep 24, 2022

Currently, I’m trying to keep track of the first 4 bytes of a file by writing them to a buffer first, and making sure the first 4 bytes aren’t a specific sequence.

Ex: File currently holds “hello”, my buffer should hold “hell”. If I write a “T” to the 3rd position in the file, I’ll write it to the buffer first: “heTl”, make sure this isn’t a specific sequence of characters, then continue with the file write.

I’m having a strange issue when writing to this buffer more than once. As one example (printing the chars as numbers to see if there’s some sort of pattern):

Data to be written: “5GIAE”. This gets correctly written to the buffer (53, 71, 73, 65).

Then I try writing “D” to the second position of the file. The buffer becomes (53, 0, 73, 65). File write of course goes through correctly and gives “5DIAE”. But as you can see, for some reason the location of the write became a 0. In other occasions, it went to “l” (the letter).

Another example, if I try to write “5” at the start, then “D” in the second position, then “B” in the 3rd position, the file will be written correctly, but my buffer holds

[53, 0, 0, 0], then [53, 0, 0, 0], then [53, 0, 67, 0]


[5, , , ], then [5, , , ] then [5, , C, ]

The data is passed into the function that does this as a void pointer. I cast it to char, and write it to the buffer

This is my code:

//GLOBAL typedef struct _FileInternal { FILE* fp; char mem[4]; } fileInternal; fileInternal *f; int * cur_pos; // holds the current position of the write location in the file // in the open file function: f = malloc(sizeof(fileInternal)); bzero(f, sizeof(fileInternal)); ... //in the write to file function: if (*cur_pos < 4) { for(int i = *cur_pos; i < (*cur_pos + num_bytes); i++){ printf("data[%d] = %cn", i, *((char *)data + i)); //This correctly prints any data that will be written to the 4-byte buffer f->mem[i] = *((char *)data + i); } 

So it looks like the first write works, but any subsequent ones, even if in empty spaces, are messed up.

It looks like these spaces that hold the incorrect characters may be consistently set to the same values. Not sure what would cause this, though

Thanks for any help

submitted by /u/turkishjedi21
[link] [comments]

Go to Source of this post
Author Of this post: /u/turkishjedi21
Title Of post: Writing data to a pointed to buffer: incorrect behavior when overwriting
Author Link: {authorlink}