【发布时间】:2019-05-31 05:07:05
【问题描述】:
我对循环中的malloc'ed char 指针的free() 有疑问。
在char *x=malloc(30) 中,我存储了一个字符串,我用add(x,queue) 将其推入堆栈。问题是我每次迭代都malloc-ing 它,所以我需要在每次迭代中free 它,否则我在valgrind 中有内存泄漏。但是如果我将free(x); 放在while 循环的末尾,valgrind 就会遇到strcmp 的问题:
Invalid read of size 1
at 0x403045D: strcmp
by 0x048871: main(main.c 149) = else if(!strcmp(x,l))
address is 0 bytes inside block of size 30 free d
by 0x80488b8: main(main.c 164) = free(x);
block was allocked at
at 0x402c17c:malloc by main(main.c 129) =char *x=malloc(30);
这很奇怪,因为在另一个分配之前我不需要那个char *x。
有没有办法以不同的方式分配它?
while ((a = getchar()) != EOF) {
if (a == '<'){
act = 1;
}
if (act == 1) {
char *x=malloc(30);
scanf("%29[^>]s",x);
if(*x=='/'){
void *l;
l=pop_from_queue(queue);
if(l==NULL)
valid=1;
else if(!strcmp(x+1,l))
valid=0;
else
valid=1;
act=0;
}else{
push_to_queue(queue,x); //push to stack
count++;
act=0;
}
free(x);
}
}
初始化栈:
typedef struct {
void **data;
int head;
int size;
int count;
} queue_t;
queue_t* create_queue(int capacity){
queue_t *queue=calloc(sizeof(queue_t),sizeof(queue_t));
queue->head=0;
queue->data=calloc(capacity+10,sizeof(void*));
queue->count=0;
queue->size=capacity+1;
return queue;
}
弹出功能:
void* pop_from_queue(queue_t *queue){
if(queue->count==0)
return NULL;
else
queue->count--;
if(queue->head<0)
return NULL;
if(queue->head!=0)
queue->head--;
return queue->data[queue->head];
}
推送功能:
bool push_to_queue(queue_t *queue, void *data){
if(queue->count==queue->size){
queue->size+=10;
queue->data=realloc(queue->data,queue->size*sizeof(void*));
}
queue->data[queue->head++]=data;
queue->count++;
return true;
}
【问题讨论】:
-
我也鼓励你在
(*x=='/')时删除 x 以防止内存泄漏,并帮助不要做x++但strcmp(x+1,l) -
没错,但我永远不会说超过 20 个字。
-
我需要 x 用于 strcmp(x,l) 所以我不能删除它。 :( 那个 x++; 是用来从 x 中删除第一个字符的,所以我可以将它与堆栈中弹出的字符串进行比较
-
所以我需要释放(x++)?或更改 x++;
-
@Dzoey 正如我所说,最小的变化是删除
x++;并将 strcmp 修改为strcmp(x+1,l),这样你就可以在之后free(x)而不必做free(x-1)不是很清楚