简体   繁体   中英

malloc…unexpected behaviour c programming

#include<stdio.h>
#include<malloc.h>
#include<string.h>

void foo( char ** ptr)
{
   *ptr = malloc(0); // allocate some memory**
   strcpy( *ptr, "Hello World");
}

int main()
{
   char *ptr = 0;
   // call function with a pointer to pointer
   foo( &ptr );
   printf("%s\n", ptr);
   // free up the memory
   free(ptr);

   return 0;
}

and it is also running

#include<stdio.h>
#include<malloc.h>
#include<string.h>

void foo( char ** ptr)
{
   *ptr = malloc(11); // allocate some memory
   strcpy( *ptr, "Hello World");
}

int main()
{
   char *ptr = 0;
   // call function with a pointer to pointer
   foo( &ptr );
   printf("%s\n", ptr);
   // free up the memory
   free(ptr);

   return 0;
}

change malloc by any number...it is always running.how it is possible???? Hello World has 12 character so hows that possible to run in 0,12,8,any number.

You are encountering the fact that C does not do any bounds checking. So your copy to the malloc'd memory is over-running the allocation and "scribbling" on whatever memory follows. The results are undefined . It may work, it may crash, it may make you a cup of coffee. You don't know.

Incidentally, this is the kind of mistake which leads to buffer-overrun attacks.

The code has bugs in it, clearly.

There are two possibilities:

  1. You're getting "lucky" that strcpy() isn't hitting anything of consequence, so the program runs.

  2. malloc() often allocates a few more bytes than requested to better keep memory aligned. It's entirely possible that it allocates in chunks of 16 physical bytes, for example.

C doesn't care how much you actually allocate (except for 0; things can get ugly if you do so); as long as you don't overstep various arbitrary artificial bounds your program will (appear to) work. You just didn't hit one of them.

It is a common misconception that mistakes like this must cause the program to crash. In fact, the C standard explicitly says that, for undefined behavior like this, there are "this International Standard imposes no requirements."

So the program might crash right away, it might corrupt random data, or it might seem to work. It's just unsafe, like Ed said.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM