Portál AbcLinuxu, 14. července 2025 20:48


Dotaz: realloc error

13.4.2011 01:56 peter
realloc error
Přečteno: 157×
Odpovědět | Admin
Ahoj, snazim sa napisat program pre citanie zo standardneho vstupu:
size_t bufSize = 1024;
unsigned char *msg = NULL;
size_t msgBytes = 0;
size_t inputMsgBufCount = 0;
unsigned char inputBuffer[bufSize];
size_t bytesRead = 0;
unsigned char *tmp = NULL;

if ((msg = (unsigned char *)malloc(sizeof(unsigned char) * bufSize)) == NULL)
    exit(EXIT_FAILURE);
bytesRead = fread(msg, sizeof(unsigned char) * bufSize, 1, stdin);
inputMsgBufCount++;

while (bytesRead) {
    printf("iteration: %lu\n", inputMsgBufCount);
    if ( (tmp = (unsigned char *)realloc(msg, (inputMsgBufCount * bufSize) + bufSize)) != NULL ) {
         printf("reallocated\n");
        msg = tmp;
        inputMsgBufCount++;
    }
    else {
        printf("Ran out of memory\n");
        free(msg);
    }
    bytesRead = fread(inputBuffer, sizeof(unsigned char) * bufSize, 1, stdin);
    memmove((msg + (inputMsgBufCount * bufSize)), inputBuffer, bufSize);
}

free(msg);

msgBytes = (inputMsgBufCount * bufSize);

gettimeofday(&end, NULL);
printf("%10.6lf [MB/s]\n", (msgBytes / (1<<20)) / ( (end.tv_sec - start.tv_sec)
ale ked program spustim: ~# dd if=/dev/zero bs=1024 count=8 | ./test dostanem nasledujucu chybu:
iteration: 1
reallocated
iteration: 2
reallocated
iteration: 3
reallocated
iteration: 4
reallocated
iteration: 5
reallocated
iteration: 6
reallocated
iteration: 7
test(11450) malloc: *** error for object 0x100804008: incorrect checksum for freed object - object was probably modified after being freed.
*** set a breakpoint in malloc_error_break to debug
Abort trap
Cize program nemoze reallokovat pamat po 7 reallokacii. Viete mi prosim niekto poradit, stojim s tym na mrtvom bode. Dakujem.
Nástroje: Začni sledovat (0) ?Zašle upozornění na váš email při vložení nového komentáře.

Odpovědi

13.4.2011 08:47 Šangala | skóre: 56 | blog: Dutá Vrba - Wally
Rozbalit Rozbalit vše Re: realloc error
Odpovědět | | Sbalit | Link | Blokovat | Admin
Výslednou chybu způsobíte tady, píšete kam nemáte:
memmove((msg + (inputMsgBufCount * bufSize)), inputBuffer, bufSize);
A vzniká vám u inputMsgBufCount++;, jedno bych ubral (vyberte si které by to mohlo být :)), nebo celý segment před while zahodit a malinko to upravit:)
A děláte si to tím že jednou píšete tam a jednou onam - chápu to jako nějaký test, takže to inputBuffer a memmove má nějaký význam, místo čtení přímo do připraveného bufferu a nezohledňování hodnoty v bytesRead.
To, že trpíš stihomamem, ještě neznamená, že po tobě nejdou. ⰞⰏⰉⰓⰀⰜⰉ ⰗⰞⰅⰜⰘ ⰈⰅⰏⰉ ⰒⰑⰎⰉⰁⰕⰅ ⰏⰉ ⰒⰓⰄⰅⰎ ·:⁖⁘⁙†

Založit nové vláknoNahoru

Tiskni Sdílej: Linkuj Jaggni to Vybrali.sme.sk Google Del.icio.us Facebook

ISSN 1214-1267, (c) 1999-2007 Stickfish s.r.o.