C
Christian Christmann
Hi,
I'm wondering why this program does not crash with a segmentation
fault:
#include <malloc.h>
#include <string.h>
#include <stdio.h>
int main()
{
char *array;
array = (char*)malloc(10 * sizeof(char) );
if ( array == NULL )
exit( 0 );
strcpy( array, "11223456789\0");
printf( "\narray[11]: %c\n", array[11] )
return 0;
}
I allocate space for 10 characters on the system heap and then copy
a string of size 12 into the allocated space. Why does the program not
crash?
My understanding was so far:
malloc request some new free space on the system heap. So, first the
program memory manager is consulted to check if it is already assigned
some free space by the operating system that might be suitable for the
malloc request. If so, this memory segment is used. Otherwise, the
request is directed to the OS that provides some new free memory that
is now assigned to this program (process) and used for the malloc memory
allocation. However, when I call "strcpy( array, "11223456789\0")" I
write the first 10 characters to the allocated memory area.The
remaining 2 characters exceed the memory area I was granted access to
and are tried to be written to memory I have no write access to. That
illegal memory access should be noticed by the OS that terminates the
program with a segmentation fault.
Furthermore, my printf should also crash the program since I
illegally attempt to read from memory I have no access to.
Thank you.
Chris
I'm wondering why this program does not crash with a segmentation
fault:
#include <malloc.h>
#include <string.h>
#include <stdio.h>
int main()
{
char *array;
array = (char*)malloc(10 * sizeof(char) );
if ( array == NULL )
exit( 0 );
strcpy( array, "11223456789\0");
printf( "\narray[11]: %c\n", array[11] )
return 0;
}
I allocate space for 10 characters on the system heap and then copy
a string of size 12 into the allocated space. Why does the program not
crash?
My understanding was so far:
malloc request some new free space on the system heap. So, first the
program memory manager is consulted to check if it is already assigned
some free space by the operating system that might be suitable for the
malloc request. If so, this memory segment is used. Otherwise, the
request is directed to the OS that provides some new free memory that
is now assigned to this program (process) and used for the malloc memory
allocation. However, when I call "strcpy( array, "11223456789\0")" I
write the first 10 characters to the allocated memory area.The
remaining 2 characters exceed the memory area I was granted access to
and are tried to be written to memory I have no write access to. That
illegal memory access should be noticed by the OS that terminates the
program with a segmentation fault.
Furthermore, my printf should also crash the program since I
illegally attempt to read from memory I have no access to.
Thank you.
Chris