2013-02-11 79 views
0

我最近加入了重寫參數處理代碼我開始創建,並且我添加了動態內存管理函數(malloc,realloc,free)的使用情況,但添加完這些後當我嘗試執行一個示例時,發生奇怪的崩潰。動態內存管理函數的使用導致崩潰

以下是從我的節目輸出:

查爾斯@ draton-generico:〜/文檔/ C/C89/SDL_Work/2D-遊戲基$ ./game-base-02-alt- 2 - l

成功退出參數捕獲循環。

==>繼續執行。

* glibc的檢測 ./game-base-02-alt-2:realloc的():無效的下一個大小:0x000000000157c010 * *

輸出這麼多它只是掛起後。

下面是我的代碼:

/* 
* CREATED BY: Charles Edwin Swain 3rd 
* DATE OF PROJECT BEGINNING: 28/1/2013 
*/ 

#include <stdio.h> 
#include <stdlib.h> 

int main(int argc, char** argv) 
{ 
int* bse = malloc(3 + 5 + 5 + argc); 
if (bse == NULL) 
{ 
    if (fprintf(stderr, "Call to malloc failed, bse = NULL.\n==>Will now exit.\n") <= 0) exit(-2); 
    exit(-1); 
} 
*(bse + 0) = 0; 
while (*(bse + 0) < (3 + 5 + 5 + argc)) 
{ 
    *(bse + *(bse + 0)) = 0; 
    *(bse + 0) = *(bse + 0) + 1; 
} 
*(bse + 0) = 0; 
*(bse + 1) = -1; 
/*THIS DETERMINES THE SIZE OF THE LARGEST ARGV CHARACTER STRING.*/ 
while (*(bse + 3) < argc) 
{ 
    while (*(bse + 4) != -1) 
    { 
     if (argv[*(bse + 3)][*(bse + 4)] == '\0') 
     { 
      if ((*(bse + 4) + 1) > *(bse + 5)) *(bse + 5) = *(bse + 4) + 1; 
      *(bse + 4) = -1; 
     } 
     else if (*(bse + 4) == 32766) 
     { 
      *(bse + 3 + 5 + 5 + *(bse + 3)) = 1; 
      *(bse + 4) = -1; 
     } 
     else *(bse + 4) = *(bse + 4) + 1; 
    } 
    *(bse + 3) = *(bse + 3) + 1; 
    *(bse + 4) = 0; 
} 
*(bse + 3) = 0; 
/*ENSURING THAT SPACE FOR RETREIVED ARGV CHARACTER STRINGS IS AT LEAST THE SIZE OF THE LARGEST CHECKED FOR SPECIFIC STRING ON LINE BELOW.*/ 
if (*(bse + 5) < 10) *(bse + 5) = 10; 
/*THIS IS (IN SOME CASES WAS) THE BIG ARGV CATCHING LOOP.*/ 
/*ERASED CONTENTS OF, AM REWRITING CODE.*/ 
while (*(bse + 3) < argc) 
{ 
    *(bse + 3) = argc; 
} 
if (fprintf(stdout, "Successfully exited argument catching loop.\n==>Continuing execution.\n") <= 0) 
{ 
    while ((*(bse + 1) <= 0)&&(*(bse + 2) < 50)) 
    { 
     *(bse + 1) = fprintf(stderr, "A function (fprintf) failed when outputting a notification informing of having 'properly' left the argument catching loop.\n==>Will now exit.\n"); 
     *(bse + 2) = *(bse + 2) + 1; 
    } 
    free(bse); 
    exit(-1); 
} 

/*SET DEFAULTS HERE*/ 

bse = realloc(bse, 3); 
if (bse == NULL) 
{ 
    if (fprintf(stderr, "Call to realloc failed, bse = NULL.\n==>Will now exit.\n") <= 0) exit(-2); 
    exit(-1); 
} 

/*END OF CODE.*/ 
free(bse); 
exit(0); 
} 

我很想把它變成一個學習的經驗。

回答

2

malloc()realloc()不知道要在返回的指針指向的內存中存儲什麼樣的數據類型。所以他們只是分配一些字節 - 他們不會奇蹟般地將它們的參數乘以sizeof(int)。所以,你想要的是:

int *bse = malloc((3 + 5 + 5 + argc) * sizeof(*bse)); 

realloc()的一致好評。

+0

謝謝您的輸入。 – Draeton 2013-02-11 20:45:50

+0

@Draeton不客氣。 – 2013-02-11 20:46:21