#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>
struct Person{
char *name;
char sex;
int age;
struct Person *ancestor;
int n;
};
void p_person(struct Person *this);
struct Person *stack_init()
{
struct Person *this=malloc(sizeof(struct Person));
assert(this!=NULL);
this->name=strdup("NULL");
this->sex='0';
this->age=-1;
this->ancestor=NULL;
this->n=1;
return this;
}
struct Person *pushPerson(struct Person *this, char *name, char sex, int age)
{
assert(this!=NULL);
int n=this->n+1;
this=realloc(this,sizeof(struct Person)*n);
this[n-1].name=strdup(name);
this[n-1].sex=sex;
this[n-1].age=age;
this[n-1].ancestor=&this[n-2];
printf("pushing new person onto stack\n");
printf("stack increasing to %d\n",this->n);
p_person(&this[n-1]);
this->n=this->n+1;
/*p_person(this[n-1].ancestor); //it works*/
printf("----------------\n\n");
return this;
}
struct Person *popPerson(struct Person *this)
{
assert(this!=NULL);
printf("Person being popped:\n");
p_person(&this[this->n-1]);
printf("resizing stack to %d\n", this->n-2);
printf("----------------\n\n");
free(this[this->n-1].name);
int n=this->n-1;
this=realloc(this,sizeof(struct Person)*n);
this->n=this->n-1;
return this;
}
void p_person(struct Person *this)
{
printf("Name: %s\n",this->name);
printf("Sex: %c\n",this->sex);
printf("Age: %d\n",this->age);
}
void p_person_stack(struct Person *this)
{
printf("printing stack...........\n");
struct Person *current;
int i;
for(i=1;i<this->n;i++)
{
current=&this[i];
p_person(current);
printf("---------\n");
}
printf("stack printed~~~~~~~~~~\n\n");
}
void d_person_stack(struct Person *this)
{
int i;
for(i=0;i<this->n;i++)
free(this[i].name);
free(this);
}
int main(int argc, char *argv[])
{
struct Person *people=stack_init();
people=pushPerson(people,"Mojo jojo", 'M', 33);
people=pushPerson(people,"Ali Zaheeruddin", 'M', 24);
people=pushPerson(people,"Mahdi Moosa", 'M', 24);
people=pushPerson(people,"Solid Snake", 'M', 51);
d_person_stack(people);
return 0;
}
p_person(&人[N]),其中n是堆棧如何使結構點本身沒有Valgrind的抱怨
p_person(人[N]範圍內的作品,未經Valgrind的抱怨罰款。祖先)使valgrind抱怨大小爲x的無效讀取取決於它在結構中讀取的內容Person例如char性別將爲x = 1 這裏的例外是當n是堆棧的結尾時(在這種情況下爲4)valgrind會沒有抱怨,對於n的所有情況,結果將被打印罰款。
這是什麼,如果我做p_person(人[N] .ancestor),其中n 小於堆的端面的valgrind會說一個例子
大小8 名稱的無效讀:阿里Zaheeruddin 的無效讀取大小1 性別:男 的無效讀取大小4 年齡:24
在(array-)指示上使用減法很容易出錯,請儘量避免它。 – alk 2013-02-14 08:03:30
我應該用什麼來代替? – lost 2013-02-14 11:03:22
OT:如果可能,請使用修改或不同的算法。例如,如果將'int n = this-> n + 1;'改爲'int n = this-> n;'可以避免所有出現的'n-1'。這不是關於解決您的具體問題,而是關於如何通過概念/方法來實現更穩定/節省的代碼。 – alk 2013-02-14 11:44:41