Strcpy function in c - strcpy

Output is:Hello
Hello
As you can see the image Can someone tell why I am getting this output!
Destination is Capable of holding only one character then how it can print entire string.

Please include the core part of your code otherwise we can't help you.
However, keep in mind that in C there is no automatic memory allocation, garbage collector and string type (which is an array of characters instead).
strcpy copies the entire source string to the pointer specified as the destination and stops only when it finds the NULL or \0 character regardless of how large the destination buffer is.
What happens is definitely a buffer overflow, the data following the destination buffer (of one byte) is overwritten, potentially causing program instability and data corruption.

Related

Why is a buffer used in Win32 API syscall cast to [1<<20]<type> array?

I'm writing a golang application which interacts with Windows Services using the windows/svc package.
When I'm looking at the package source code how syscalls are being done I see interesting cast construct:
name := syscall.UTF16ToString((*[1 << 20]uint16)(unsafe.Pointer(s.ServiceName))[:]
Extracted from mgr.go
This is a common patttern when dealing with Win32 API when one needs to pass a pre-allocated buffer to receive a value from Win32 API function, usually an array or a structure.
I understand that Win API returns a unicode string represented by its pointer and it is passed to the syscall.UTF16ToString(s []uint16) function to convert it to the go string in this case.
I'm confused from the part when an unsafe pointer is cast to the pointer to 1M array, *[1<<20]uint16.
Why the size if 1M [1<<20]?
Buffer for a value is allocated dynamically, not with fixed size of 1M.
You need to choose a static size for the array type, so 1<<20 is chosen to be large enough to allow for any reasonable buffer returned by the call.
There is nothing special about this size, sometimes you'll see 1<<31-1 since it's the largest array for 32bit platforms, or 1<<30 since it looks nicer. It really doesn't matter as long as the type can contain the returned data.

What is the most likely reason a variable, passed as reference to a program, would have its value changed past its length?

My coworker came to me with a problem yesterday.
He has a CL with two variables defined, 10 characters each. He then calls another CL with the first variable as a parameter, and after the CL comes back (which is a long string of programs which will likely have to be manually combed through for the offending code), his first variable is unchanged, but the first 5 characters of his second variable are blanked out.
Because the parameters are passed by reference there is obviously something that is able to affect more than the 10 bytes allotted and it is overflowing to the variable defined immediately after it in memory, but I'm wondering what common examples of this would be (that would not result in some kind of explicit error). Another program that is getting this address passed to it that has its parameters defined with 15 bytes? Using a pointer to the address and then dereferencing and assigning a 15 character string? This is V7R1.
In the meantime he stuck another variable between the two to act as a buffer lol. Interestingly enough, variables that are not assigned a value are never initialized so they are not given any space in memory. Interesting thing to discover when playing around with this.
All is takes is for a program further down in the call stack to have a parameter mis-defined
calling program
/*pgm a*/
pgm
dcl &parm1 char(10) value('Hello')
dcl &parm2 char(10) value('Charles')
call pgmb parm(&parm1 &parm2)
endpgm
called program
/*pgm b*/
pgm parm(&parmA &parmB)
dcl &parmA char(15)
dcl &parmB char(10)
chgvar &parmA value('Bye')
endpgm
Note: It's not guaranteed to break, it might work fine, till some PTF is applied that changes the internals of the OS or just the compiler.
I personally saw where an RPG III program had been working "fine" for years, that broke when converted to RPGIV due to differences in how the compiler laid out memory. The RPG III program was corrupting unused memory, but at RPGIV the corrupted memory had been important.
Bottom line, count yourself lucky that an error is being thrown...trace down through the call stack to find the mismatch.
Defining another variable between the two variables won't necessarily make a difference. There is no guarantee that variables are laid out in storage in the same order they are defined in the program.
To ensure there is additional storage following a variable, the extra storage must be defined explicitly.
In CL, do it like this. This will add a guaranteed extra 90 bytes following &MYVAR.
dcl &myvar_stg type(*char) len(100)
dcl &myvar type(*char) stg(*defined) len(10) defvar(&myvar_stg 1)
Assuming all the programs involved are debuggable, you can find out exactly where the storage is getting corrupted by putting a watch on the second variable in debug.
In the debugger, use the "watch" command and then let the program run.
===> watch &myvar2
You'll get a watch breakpoint on the next debuggable statement following the statement that changed the storage. Usually, the next debuggable statement is in the same program that changed the storage.

What is the QBytearray, returned by QFile readAll()

I want to ask that if the QFile().readAll () , returns a QByte Array then does it create a byte array on Physical memory or just provides a linked list address containing the positions of Bytes?.
can it create problem in the case of large files which are in GBs.
Yes, it does create a byte array in RAM, copying the whole memory that is in your hard drive. So you will run into issues running QFile::readAll() on huge files.
The documentation for QString QTextStream::readAll() says:
Reads the entire content of the stream, and returns it as a QString.
Avoid this function when working on large files, as it will consume a
significant amount of memory.
It is not mentioned for QByteArray QIODevice::readAll() (inherited by QFile), but it will be the same, since there is no way the pointers in a QByteArray can point somewhere in your hard disk (must be an address in the virtual memory allocated to the program by the OS, i.e. the stack or the heap).

Bus error when recompiling the binary

Sometimes, on various Unix architectures, recompiling a program while it is running causes the program to crash with a "Bus error". Can anyone explain under which conditions this happens? First, how can updating the binary on disk do anything to the code in memory? The only thing I can imagine is that some systems mmap the code into memory and when the compiler rewrites the disk image, this causes the mmap to become invalid. What would the advantages be of such a method? It seems very suboptimal to be able to crash running codes by changing the executable.
On local filesystems, all major Unix-like systems support solving this problem by removing the file. The old vnode stays open and, even after the directory entry is gone and then reused for the new image, the old file is still there, unchanged, and now unnamed, until the last reference to it (in this case the kernel) goes away.
But if you just start rewriting it, then yes, it is mmap(3)'ed. When the block is rewritten one of two things can happen depending on which mmap(3) options the dynamic linker uses:
the kernel will invalidate the corresponding page, or
the disk image will change but existing memory pages will not
Either way, the running program is possibly in trouble. In the first case, it is essentially guaranteed to blow up, and in the second case it will get clobbered unless all of the pages have been referenced, paged in, and are never dropped.
There were two mmap flags intended to fix this. One was MAP_DENYWRITE (prevent writes) and the other was MAP_COPY, which kept a pure version of the original and prevented writers from changing the mapped image.
But DENYWRITE has been disabled for security reasons, and COPY is not implemented in any major Unix-like system.
Well this is a bit complex scenario that might be happening in your case. The reason of this error is normally the Memory Alignment issue. The Bus Error is more common to FreeBSD based system. Consider a scenario that you have a structure something like,
struct MyStruct {
char ch[29]; // 29 bytes
int32 i; // 4 bytes
}
So the total size of this structure would be 33 bytes. Now consider a system where you have 32 byte cache lines. This structure cannot be loaded in a single cache line. Now consider following statements
Struct MyStruct abc;
char *cptr = &abc; // char point points at start of structure
int32 *iptr = (cptr + 1) // iptr points at 2nd byte of structure.
Now total structure size is 33 bytes your int pointer points at 2nd byte so you can 32 byte read data from int pointer (because total size of allocated memory is 33 bytes). But when you try to read it and if the structure is allocated at the border of a cache line then it is not possible for OS to read 32 bytes in a single call. Because current cache line only contains 31 bytes data and remaining 1 bytes is on next cache line. This will result into an invalid address and will give "Buss Error". Most operating systems handle this scenario by generating two memory read calls internally but some Unix systems don't handle this scenario. To avoid this, it is recommended take care of Memory Alignment. Mostly this scenario happen when you try to type cast a structure into another datatype and try reading the memory of that structure.
The scenario is bit complex, so I am not sure if I can explain it in simpler way. I hope you understand the scenario.

Memory (sbrk) 16-byte aligned shifting on pointer access

I wrote a reasonably basic memory allocator using sbrk. I ask for a chunk of memory, say 65k and carve it up as needed for variables requesting dynamic memory. I free the memory by adding it back to the 65k block. The 65k block is derived from a union sizeof(16-bytes). Then I align the block along an even 16-byte boundary. But I'm getting unusual behavior.
Accessing the memory appears fine as I allocate and begin to populate my data structures accept that on one of my function calls, I pass a pointer to a member variable in a global structure but the address of the pointer argument doesn't map directly to the address of that member.
For example, the real address of this particular member happens to be: 0x100313d50 but when executing a particular function (nothing special) the address of the member is being represented as 0x100313d70. Inside the debugger I can query the real address and it appears correct when inside the function where this manifests. This isn't the first member being accessed either, it's the third so two prior memory accesses are fine, but during the third access I'm seeing this unusual shifting.
Is it possible that I'm accessing this memory via a misaligned block? It's possible but I'd expect the get a SIGBUS exception thrown (SPARC chip). I'm compiling using -memalign=16s so it ought to SIGBUS instead of trapping and fixing the misalignment.
All of my structures are padded on a multiple of 16-bytes: sizeof(structure)%16 = 0. Has anyone had experience with this type of behavior? Generally speaking, what type of things/stuff/etc. might cause a pointer to misrepresent a memory address?
Cheers,
Tracy.
Solaris 10, SunStudio-12, C language on modern SPARC processor (in case this helps).
I figure I should answer my own question in the event someone else out there has a similar problem.
The reason why the memory address was shifting is because a prior call to a utility function accidentally overwrote the meta-address of the global structure thusly rewriting the meta-address of that block so lookups on that block were shifted even though the actual data still resided in the original block.
In simple words, I wrote past my buffer. Since I hand out memory from the tail, overwriting would blow away my much needed meta-address for my global structure (or whatever). Now I know what undefined behavior looks like.

Resources