0

嗨,我正在学习一些调试概念。在这个程序中,我试图模拟核心转储。我希望核心会被转储但它不会生成核心。程序执行没有任何问题。

首先,我为 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
4

2 回答 2

3

如果你在内存被释放后写入内存,任何事情都可能发生。这是未定义的行为。您可以获取或不获取核心转储。在您的情况下,您不会获得核心转储,因为即使内存已被释放,您的进程仍然可以访问该内存。如果您malloc在语句之前 执行另一个操作return 0并写入该内存,则字符串“重新分配后...”很可能会被覆盖。

对于 dbx,该printf("After Free memory : %s\n",ptr);语句会产生“未分配读取”错误,因为您已打开访问检查,但如果没有 dbx,则根本没有访问检查。

为了模拟核心转储,您可以这样做:

void main()
{
  char *p = NULL ;
  *p = 'A' ;
}

这将在大多数平台上崩溃。

于 2014-02-27T09:38:14.530 回答
1

free(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-27T10:35:45.627 回答