Format
#include <string.h>
char *_debug_strncpy(char *string1, const char *string2, size_t count,
const char *filename, size_t line);
Language Level: Extension
_debug_strncpy is the debug version of strncpy. Like
strncpy, it copies count characters of string2
to string1. If count is less than or equal
to the length of string2, a null character (\0) is not
appended to the copied string. If count is greater
than the length of string2, the string1
result is padded with null characters (\0) up to length count.
_debug_strncpy validates the heap after copying the strings to the target location, and performs this check only when the target is within a heap. _debug_strncpy makes an implicit call to _heap_check. If _debug_strncpy detects a corrupted heap when it makes a call to _heap_check, _debug_strncpy will report the file name file and line number line in a message.
Note: _debug_strncpy checks only the current default heap. Therefore, this debug support will not check all heaps within applications that have multiple user heaps.
To use _debug_strncpy, you must compile with the debug memory (/Tm) compiler option. This option maps all strncpy calls to _debug_strncpy. You do not have to change your source code, in order for _debug_strncpy to verify the heap.
Note: The /Tm option maps all calls to other string functions and all calls to memory management functions (including a heap-specific version), to their debug counterparts. To prevent a call from being mapped, parenthesize the function name.
Return Value
_debug_strncpy returns a pointer to string1.
Example
This example is similar to the strncpy example, except that it
contains a programming error. The source string is too long for
the destination buffer, and the strncpy operation damages the
heap.
#include <stdlib.h> #include <stdio.h> #include <string.h>
#define SIZE 10
int main(void)
{
char *source = "1234567890123456789";
char *destination;
char *return_string;
int index = 15;
destination = (char*)malloc(SIZE); strcpy(destination, "abcdefg"),
printf("destination is originally = '%s'\n", destination);
return_string = strncpy(destination, source, index);
printf("After strncpy, destination becomes '%s'\n\n", destination);
return 0;
/****************************************************************************
The output should be similar to:
destination is originally = 'abcdefg'
End of allocated object 0x00073c80 was overwritten at 0x00073c8a.
The first eight bytes of the memory block (in hex) are: 3132333435363738.
This memory block was (re)allocated at line number 14 in strncpy.c.
Heap state was valid at line 15 of strncpy.c.
Memory error detected at line 18 of strncpy.c.
****************************************************************************/
}
![]()
Managing Memory
with Multiple Heaps
![]()
_debug_memcpy -- Copy Bytes
_debug_strcpy -- Copy Strings
_heap_check -- Validate Default Memory
Heap
strcpy -- Copy Strings
strncpy -- Copy Strings
<string.h>
/Tm compiler option