嗨,我正在学习一些调试概念。在这个程序中,我试图模拟核心转储。我希望核心会被抛弃,但它不是生成核心。程序执行没有任何问题。
首先,我为ptr分配20个字节。我将一个新字符串复制到ptr。然后,我释放ptr,然后打印ptr它没有任何pblm工作。最后,我将分配一些其他字符串,这一次它可能会生成核心转储。但我没有得到任何核心垃圾。有谁能解释一下为什么它不产生核心转储。
int main()
{
   char *ptr;
   ptr =(char*)  malloc (20);
   strcpy(ptr,"MemoryOperations");
   printf("Before Free memory : %s\n",ptr);
   free(ptr);
   printf("After Free memory : %s\n",ptr);
   strcpy(ptr,"MemReassign");
   printf("After Re Assigning : %s\n",ptr);
   return 0;
}与我使用dbx运行的代码相同,
(dbx) check -all
access checking - ON
memuse checking - ON
(dbx) run
Running: a.out 
(process id 19081)
RTC: Enabling Error Checking...
RTC: Running program...
Before Free memory : MemoryOperations
Read from unallocated (rua):
Attempting to read 1 byte at address 0x100101a48
which is 2232 bytes into the heap; no blocks allocated
stopped in _ndoprnt at 0xffffffff671abbf0
0xffffffff671abbf0: _ndoprnt+0x1c04:    call     _PROCEDURE_LINKAGE_TABLE_+0x620 [PLT] ! 0xffffffff67340d20
(dbx) exit发布于 2014-02-27 10:35:45
自由( ptr )不修改ptr的值。它只是标记相应的位置是可用的重新分配。
A block of memory previously allocated by a call to malloc, calloc or realloc is
deallocated, making it available again for further allocations.
Notice that this function does not change the value of ptr itself, 
hence it still points to the same (now invalid) location.
--cplusplus.com因此,如果您实际上想要生成核心转储,尝试一些确定的结果,然后尝试一些疯狂的事情,比如:
char d=10/0;  //arithematic
char *a=malloc(1);
free(a);
a=NULL;   //this is important after free.
*a=100;发布于 2014-02-27 09:38:14
如果在内存释放后写入内存,任何事情都可能发生。这是不确定的行为。你可以得到一个核心转储物。在您的情况下,您没有得到一个核心转储,因为内存,即使它已经释放,仍然可以由您的进程访问。如果您要在malloc语句之前执行另一个return 0语句并写入该内存,则字符串“重新赋值后.”很可能会被覆盖。
对于dbx,printf("After Free memory : %s\n",ptr);语句会产生一个“从未分配的数据中读取”错误,因为您已经打开了访问检查,但是如果没有dbx,就根本不存在访问检查。
为了模拟核心转储,您可以这样做:
void main()
{
  char *p = NULL ;
  *p = 'A' ;
}这将在大多数平台上崩溃。
https://stackoverflow.com/questions/22064341
复制相似问题