嗨,我正在学习一些调试概念。在这个程序中,我正在尝试模拟核心转储。我期待核心将被倾倒,但它不是生成核心。程序执行没有任何问题。

首先我为PTR分配20个字节。我将一个新字符串复制到PTR。然后我免费PTR然后在没有任何PBLM的情况下打印PTR。最后,我重新分配一些其他字符串,我期望这次可能会生成核心转储。但我没有得到任何核心转储。任何人都可以解释为什么它不是生成的核心转储。

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
.

有帮助吗?

解决方案

免费(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;
.

其他提示

如果在释放后写入内存,任何事情都会发生任何事情。这是未定义的行为。您可以获得核心转储。在您的情况下,您不会因为内存而获得核心转储,即使它已被释放,也仍然可以通过您的进程访问。Buf如果您可以在malloc语句之前进行另一个生成的世代odicetagcode并将其写入该内存,则最有可能覆盖字符串“重新分配...”。

与dbx,return 0语句产生“从未分配的”错误,因为您已在访问检查时已切换,但没有DBX根本没有访问检查。

模拟核心转储,您可以执行以下操作:

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

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top