memcpy() copies more bytes than expected [closed] - c

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to memcpy 'x' bytes from one array to another starting from some some offset within the array
strlen(buf) // source array already contains 144 bytes
// len - 500 bytes
memcpy(&buf[start], &content[no_of_byes], len)
After this operation on performing strlen(buf), I am getting total of 752, instead of 644. I do not understand the reason.
I even tried copying 500 bytes from content array into another buffer2 and then copying it into buffer, still same result.

strlen tries to calculate the length of a string, in the sense that it keeps on counting bytes from the beginning of the buffer till encounters a '\0' whereas memcpy works only with bytes.
I guess your problem stems from not understanding this.
You may be having a string of 752 and are trying copy some of the bytes inbetween from an offset to the beginning of the buffer (this info not very clear from your question). But, in this process, your '\0' probably remains at the same place leading to the strlen giving the same result.
My suggestion is to differentiate strings and normal buffers and use appropriate system calls for these two operations.

Related

In C, is there a way to calculate the size of allocated memory filled with null-terminators? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I need something like strlen but the string is filled with only null-terminators "\0\0\0\0\0\0\0" and I need to fill it with another character up until (not including) the last \0 like so "FFFFFF\0". Is there a way to calculate the size without errors?
I had to implement bzero for a school project called "libft". Then I was tasked with implementing strcpy and I saw in the man pages that dest needs to be large enough to receive the copy of src so I want to account for a situation where bzero was used on dest and strcpy doesn't allow me to pass the size of dest as a parameter. I was just wondering (out of curiosity) how I would know how big dest is because I know that strcpy does not account for this. There is a warning in the man page "Beware of buffer overruns! (See BUGS.)".
I realise now that this might be impossible in C.
What you're asking is whether you can know how much memory has been allocated.
If it was allocated with malloc, no.
If it's an array allocated on the stack, like char foo[10], yes you can use sizeof(foo), but that doesn't tell you anything you didn't already know.
If you need to know the allocated size of the string, you need to remember it at allocation time and pass it around. You can use an extra variable, or you can make a struct which has both the string and size.
No, there is no generic way. If your char * input fulfils *input == '\0', then it is a null terminated string of size zero, and we cannot know whether input[n] is valid for any n > 0.
However, if you had control over the allocation of input or any other hint, you can use that information, e.g.
input = malloc(N);
/* use N */
Otherwise, it's completely opaque.

After writing to a place in mmapped memory, when printing it out afterwards, it's not written anymore [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm trying to mmap a bunch of integers in a multdimensional array into mmapped memory. I know the calculations work because I printed out the multidimensional array and it prints the correct values. And I compared the values in the double for loop, printing the value of the multidimensional array and the value at the place in mmapped memory after it's been assigned, and they both correspond to the same values.
When I leave the for loop and print out what's in the mmapped memory, only the first and last values print correctly. In contrast, when I print out the multidimensional array directly, it does print the correct values. Am I writing to the mmapped memory wrong?
I don't think this
199 args->shmem3[r+c] = m[r][c];
Is what you want. Rather:
199 args->shmem3[r*args->matrix_size+c] = m[r][c];

WinAPI ReadFile stops when reaching null [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'm trying to write a very simple win32 program. I open a file for reading using CreateFile(), and then read it's content using ReadFile()
HANDLE hfile=CreatFileW(L"Capturejpg.jpg", GENERIC_READ, 0,
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,NULL);
bReadResult=ReadFile(hFile, ReadBuff, BUFFERSIZE-1, &dwBytes, &OL);
when I'm reading a .txt file for example, this works just fine, the problem is when the file I am reading contains NULL (which is the case with most files) then ReadFile function stops reading(or maybe writing bytes to ReadBuff) when reaching the first NULL.
before asking I searched and found two answers.
use something other that char array and char *: for this, I don't know what else I can use, cause my goal is to read the file and search for the files extension(for example if it's .gif then the first 3 characters read "Gif")
change DCB: the problem with this one is that I have no idea what DCB is actually, how to change it, and change exactly what in it.
EDIT: other posts with the same problem: this one and this one
ReadFile does not care one bit about the content that it reads. It will quite happily read zero bytes and continue reading beyond that point in the file. It wouldn't be much use if it could not do that.
You have just misdiagnosed the problem. You have read into a character array ReadBuffer and then printed like this:
printf("%s", ReadBuffer);
Now, printf will indeed stop when it reaches a zero byte. You will need to find some other way to output the content of this file.

C - Read from file 1 line at a time without using fgets / getline [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Schoolwork — No code please. Pseudo code ok.
We are only allowed to use 3 libc functions: read, malloc, and free. However, during the course of school we have implemented and written many of our own versions of libc functions, and those ones we are allowed to use. I would list them, but there are about 50 of them, so instead I will be sure to mention which ones I cannot use.
My question...What are the steps I must take to read a line from a file and store that line as a string, without the \n? Is anyone able to walk me through the process? Because right now, I don't even know where to begin. I know how to use read, and I would consider myself somewhere between beginner and intermediate skill level with C, but after spending an entire day searching Google, every time this same question has been asked, the accepted answer always involves using fgets or getline, which we are not allowed to use, for obvious reasons. I have implemented my own versions of many libc functions that could potentially help in this project, but anything that would make this project quick and easy is obviously not allowed.
Again, please no code, though pseudo code is fine, but I would much prefer it if somebody could help me better understand what I need to 'tell the computer' to do, and from there I should be fine to write the code myself.
Pseudo-code to read 1 line
buffer to 0, size to 0, size_used to 0
loop
read 1 character
no success? - break loop
size_used >= size
make buffer bigger (maybe 2x, at least 1)
[This involves allocating a new buffer, copy existing data, freeing old buffer]
add character to buffer
was character a \n? - break loop
Nothing read?
return NULL
right-size buffer to size_used+1
append \0
return buffer (calling code needs to eventual free it.)
Lots of efficiency improvement are possible. I suggest starting with a basic version, get functionality correct and then consider improvements such as
Performance: read from the file, maybe 4k bytes at a time.
Performance: re-using the returned buffer.
Make robust and check for allocation failures.

Best way to read a file line-by-line in C using mmap? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
The following code shows how to read part of a file using the mmap command:
addr = mmap(NULL, length + offset - pa_offset, PROT_READ,
MAP_PRIVATE, fd, pa_offset);
if (addr == MAP_FAILED)
handle_error("mmap");
s = write(STDOUT_FILENO, addr + offset - pa_offset, length);
if (s != length) {
if (s == -1)
handle_error("write");
If addr is a char*, how would I split the result into lines? Or is there a better way to read lines from a text file using mmap?
It's unclear why you want to mmap the file in the first place. I suppose it is for performance, but unless you have determined through performance testing that your program does not run fast enough and that I/O on the file in question is a significant bottleneck for it, then such a step would be jumping the gun.
Nevertheless, if you are determined to mmap the file, and you must also perform some form of line-by-line processing on it, then your alternatives for identifying line breaks are:
examine the bytes to see which ones are line terminators.
Details depend on exactly what you want to do. You can be more efficient if you can test for newlines as you scan the data, but if necessary, then you can scan ahead of the current processing position to find the next line terminator, so as to know ahead of time where it is. You can write that as a simple loop, or you might find it convenient to use the memchr() function.
Do bear in mind, too, that you probably don't want to modify the data (and can't if you map it with PROT_READ, as you do), so you cannot expect to replace line terminators with string terminators unless you copy the data to a separate buffer. Also, the last line may or may not have a terminator. You will therefore need to exercise caution with the standard string functions.

Resources