programing

c 프로그램에서 더블 프리 또는 손상(! prev) 오류가 발생

skycolor 2023. 9. 24. 12:42
반응형

c 프로그램에서 더블 프리 또는 손상(! prev) 오류가 발생

c 프로그램을 실행할 때 다음 오류가 발생합니다.

*** glibc detected *** ./a.out: double free or corruption (!prev): 0x080b8008 ***

프로그램이 끝날 때 프리()가 호출되었기 때문이라고 생각하지만, 이에 앞서 멀록의 메모리가 어디서 해방되는지 알 수가 없습니다.코드는 다음과 같습니다.

#include <stdio.h>
#include <stdlib.h> //malloc
#include <math.h>  //sine

#define TIME 255
#define HARM 32

int main (void) {
    double sineRads;
    double sine;
    int tcount = 0;
    int hcount = 0;
    /* allocate some heap memory for the large array of waveform data */
    double *ptr = malloc(sizeof(double *) * TIME);
    if (NULL == ptr) {
        printf("ERROR: couldn't allocate waveform memory!\n");
    } else {
        /*evaluate and add harmonic amplitudes for each time step */
        for(tcount = 0; tcount <= TIME; tcount++){
            for(hcount = 0; hcount <= HARM; hcount++){
                sineRads = ((double)tcount / (double)TIME) * (2*M_PI); //angular frequency
                sineRads *= (hcount + 1); //scale frequency by harmonic number
                sine = sin(sineRads); 
                *(ptr+tcount) += sine; //add to other results for this time step
            }
        }
        free(ptr);
        ptr = NULL;     
    }
    return 0;
}

이 문서는 다음과 같이 구성됩니다.

gcc -Wall -g -lm test.c

발그린드:

valgrind --leak-check=yes ./a.out

다음을 제공:

    ==3028== Memcheck, a memory error detector
==3028== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==3028== Using Valgrind-3.6.0.SVN-Debian and LibVEX; rerun with -h for copyright info
==3028== Command: ./a.out
==3028== 
==3028== Invalid read of size 8
==3028==    at 0x8048580: main (test.c:25)
==3028==  Address 0x41ca420 is 1,016 bytes inside a block of size 1,020 alloc'd
==3028==    at 0x4024F20: malloc (vg_replace_malloc.c:236)
==3028==    by 0x80484F8: main (test.c:15)
==3028== 
==3028== Invalid write of size 8
==3028==    at 0x8048586: main (test.c:25)
==3028==  Address 0x41ca420 is 1,016 bytes inside a block of size 1,020 alloc'd
==3028==    at 0x4024F20: malloc (vg_replace_malloc.c:236)
==3028==    by 0x80484F8: main (test.c:15)
==3028== 
==3028== 
==3028== HEAP SUMMARY:
==3028==     in use at exit: 0 bytes in 0 blocks
==3028==   total heap usage: 1 allocs, 1 frees, 1,020 bytes allocated
==3028== 
==3028== All heap blocks were freed -- no leaks are possible
==3028== 
==3028== For counts of detected and suppressed errors, rerun with: -v
==3028== ERROR SUMMARY: 8514 errors from 2 contexts (suppressed: 14 from 7)

저는 자신의 메모리를 자동으로 관리하지는 않지만(따라서 이 연습은 조금 배우기 위해 c에서) 막히는 언어에 대한 경험이 많지 않습니다.어떤 도움이라도 주시면 감사하겠습니다.

코드는 부가적인 오디오 합성기의 일부로 되어 있습니다.그런 점에서 작동하며 ptr에 저장된 정확한 출력을 제공합니다.

감사해요.

double *ptr = malloc(sizeof(double *) * TIME);
/* ... */
for(tcount = 0; tcount <= TIME; tcount++)
                         ^^
  • 당신은 준비를 너무 서두르고 있습니다.둘 중 하나 변경<=로.<또는 할당SIZE + 1요소들
  • 당신의.malloc틀렸다, 당신은 원할 것입니다.sizeof(double)대신에sizeof(double *)
  • ~하듯이ouah댓글들은 당신의 부패 문제와 직접적으로 연결되지는 않지만, 당신이 사용하고 있는*(ptr+tcount)초기화하지 않고

  • 스타일 노트와 마찬가지로 사용하는 것이 좋습니다.ptr[tcount]대신에*(ptr + tcount)
  • 그럴 필요 없어요malloc+free이미 알고 계시겠지만SIZE

줄 바꿈

double *ptr = malloc(sizeof(double *) * TIME);

로.

double *ptr = malloc(sizeof(double) * TIME);

1 - 당신의 malloc()이 틀렸습니다.
2 - 할당된 메모리의 한계를 초과합니다.
3 - 할당된 메모리를 초기화해야 합니다.

여기 필요한 모든 변경 사항이 포함된 프로그램이 있습니다.내가 정리하고 뛰었더니...오류 또는 경고 없음.

#include <stdio.h>
#include <stdlib.h> //malloc
#include <math.h>  //sine
#include <string.h>

#define TIME 255
#define HARM 32

int main (void) {
    double sineRads;
    double sine;
    int tcount = 0;
    int hcount = 0;
    /* allocate some heap memory for the large array of waveform data */
    double *ptr = malloc(sizeof(double) * TIME);
     //memset( ptr, 0x00, sizeof(double) * TIME);  may not always set double to 0
    for( tcount = 0; tcount < TIME; tcount++ )
    {
         ptr[tcount] = 0; 
    }

    tcount = 0;
    if (NULL == ptr) {
        printf("ERROR: couldn't allocate waveform memory!\n");
    } else {
        /*evaluate and add harmonic amplitudes for each time step */
        for(tcount = 0; tcount < TIME; tcount++){
            for(hcount = 0; hcount <= HARM; hcount++){
                sineRads = ((double)tcount / (double)TIME) * (2*M_PI); //angular frequency
                sineRads *= (hcount + 1); //scale frequency by harmonic number
                sine = sin(sineRads); 
                ptr[tcount] += sine; //add to other results for this time step
            }
        }
        free(ptr);
        ptr = NULL;     
    }
    return 0;
}

코드를 다 확인하지는 않았지만 malloc call에 오류가 있는 것 같습니다.교체해야 합니다.

 double *ptr = malloc(sizeof(double*) * TIME);

위해서

 double *ptr = malloc(sizeof(double) * TIME);

두 배에 대한 크기를 할당하려는 경우(두 배에 대한 포인터의 크기가 아님).

언급URL : https://stackoverflow.com/questions/12230788/double-free-or-corruption-prev-error-in-c-program

반응형