2014-03-13 56 views
0

我已經看過了類似的問題在stackoverflow,但我仍然不知道如何解決它。*** glibc檢測到***無效指針:0x00000031bee21188

#include <stdio.h> 
#include <stdlib.h> 
#include <ctype.h> 
extern char * pop(); 
extern void push(char *); 
int i; 
int j=0; 
//Resize the array to 1.1 it's size 
void reSize(char* tag){ 

char *temp = malloc(1.1*sizeof(tag)); 
for (i=0;i<(sizeof(tag)/sizeof(tag[0]));i++){ 
    *(temp+i) = *(tag+i); 
} 
free(tag); 
tag = temp; 
} 
int compare(char* tag, char* popVal){ 
i=0;  
while (i<sizeof(tag)/sizeof(tag[0])){ 
    if (*(tag+i) == *(popVal+i)){ 
     i++; 
    }else{ 
     return 0; 
    } 
} 
return 1; 
} 
void dothis(){ 
int ch; 
int n=0; 
char *tag = malloc(10* sizeof(char)); 
char *popVal; 
while ((ch = getchar()) != '>'){ 
    tag[n] = ch;   
    n++; 
    if (n > (sizeof(tag)/sizeof(tag[0]))-1){ 
     reSize(tag); 
    } 
} 
if (*tag == '/'){ 
    popVal = malloc(sizeof(tag));  
    popVal = pop(); 
    j--;  
    if (!(compare(tag,popVal))){ // Compare will return 1 if the same 
     printf("Invalid"); 
     exit(1); 
    } 

}else{ 
    push(tag); 
    j++; 
} 
free(tag); 
free(popVal); 
} 

int main(int argc, char * argv[]) 
{ 
    int ch; 
    while ((ch = getchar()) != EOF) { 
if (!(isalpha(ch) || ch == '<')) 
    continue; 
dothis(); 

    } 
if (j != 0){ 
    printf("Invalid\n");   
    exit(1); 
} 

    printf("Valid\n");   
    exit(0); 
} 

那麼外部方法:

#include <stdio.h> 
#include <stdlib.h> 
static int top = 0; 
static char * stack[100]; 

int isEmpty() 
{ 
    return !(top); 
} 

char * pop() 
{ 
if (isEmpty()){ 
    fprintf(stderr, "Stack is empty");  
    exit(1); 
} 
top--; 
    return (char *) stack[top]; 
} 

    void push(char * thing2push) 
{ 
    if (top == 100){ 
    fprintf(stderr, "Too many things in the stack");   
    exit(1); 
}else{ 
    stack[top] = thing2push;  
    top++; 
} 
} 

在前面的問題,所選擇的答案是「指針傳遞到你沒有使用malloc肯定不會做好事分配的內存。」但我「敢肯定我分配一切

+0

'char *'不會默認爲'NULL',因此您應該在您對其執行任何操作之前迭代您的'stack'並將它們明確設置爲NULL。 – AndyG

+0

當你有一個指針時,比如'char * tag',對該指針做'sizeof'會返回*指針的大小*和*而不是它指向的內容。 –

+0

您也有內存泄漏,因爲您分配內存並直接用另一個指針覆蓋指針,從而丟失第一個指針。 –

回答

0

這裏有一個錯誤:

popVal = malloc(sizeof(tag));  
popVal = pop(); 

你malloc一個區域,然後立即失去該值,取而代之的是來自pop()的東西。

這是最絕對是一個錯誤:

while ((ch = getchar()) != '>'){ 
    tag[n] = ch;   
    n++; 
    if (n > (sizeof(tag)/sizeof(tag[0]))-1){ 

分配到標籤[N]檢查n的範圍之前。當你確實使用sizeof(tag)後檢查n的範圍。 tag是一個指針。它的大小是4(32位)或8(64位)。這兩個尺寸與tag[n]寫入無效內存之前n之間的大小沒有任何關係。

另一個錯誤:

char * pop() 
{ 
if (isEmpty()){ 
    fprintf(stderr, "Stack is empty");  
    exit(1); 
} 
top--; 
    return (char *) stack[top]; 
} 

如果你是一個開始C程序員,從未將指針。因爲我懷疑你已經學到了足夠的知識,但不知道這是好還是壞的想法。

類型系統存在的理由很充分,如果它抱怨某些類型不匹配,那麼它比你更有可能是正確的。

+0

對於第一個bug,我想popVal = pop(),但是pop會返回一個與標籤大小相同的指針。\ 對於第二個bug,我是不是通過初始化標籤大小爲10 ?那麼每次n接近標籤數組的大小,我都會重新分配它。 對於第三個錯誤,我們的教授給了我們代碼,但是當我自己編寫代碼時,我會記住 –

+0

@ user3365695:在C語言中,局部變量在聲明時爲它們分配了內存,這意味着4或8字節的指針已經提供,你沒有理由malloc –

+0

@ user3365695:我想我解釋了爲什麼標籤不是大小10. tag是一個指針,它指向一個內存區域,你分配malloc。但是指針的大小隻是指針的大小,並不是它指向的大小。 –

相關問題