문제

안녕하세요 저는 디버깅 개념을 배우고 있습니다.이 프로그램에서는 코어 덤프를 시뮬레이션하려고 합니다.코어가 덤프될 것으로 예상하지만 코어를 생성하지는 않습니다.문제없이 프로그램이 실행됩니다.

먼저 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
도움이 되었습니까?

해결책

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;
.

다른 팁

메모리가 해제된 후 메모리에 쓰면 어떤 일이든 일어날 수 있습니다.정의되지 않은 동작입니다.코어 덤프를 얻을 수도 있고 그렇지 않을 수도 있습니다.귀하의 경우에는 메모리가 해제되었더라도 프로세스에서 여전히 액세스할 수 있기 때문에 코어 덤프를 얻지 못합니다.하지만 다른 일을 하고 싶다면 malloc 직전에 return 0 명령문을 작성하고 해당 메모리에 쓰면 "After Re Assigning ..." 문자열을 덮어쓰게 될 가능성이 높습니다.

dbx를 사용하면 printf("After Free memory : %s\n",ptr); 액세스 확인을 켰지만 dbx가 없으면 액세스 확인이 전혀 없기 때문에 문에서 "할당되지 않은 항목 읽기" 오류가 발생합니다.

코어 덤프를 시뮬레이션하려면 다음을 수행할 수 있습니다.

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

대부분의 플랫폼에서 충돌이 발생합니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top