2014-03-13 45 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。但是指针的大小只是指针的大小,并不是它指向的大小。 –

相关问题