I have the following code:
#include <stdio.h>
#include <stdlib.h>
struct R1 {
char *name;
int index;
float (*foo)(void);
struct R1 *next;
};
float bogus(void);
void PrintList(struct R1 *ptr);
struct R1 *newlist(int i);
int main(void) {
struct R1 foobar = { "mytest", 0, bogus, NULL};
foobar.next = newlist(foobar.index);
PrintList(&foobar);
PrintList(foobar.next);
free(foobar.next);
return 0;
}
float bogus(void) {
return rand() % 6;
}
void PrintList(struct R1 *ptr) {
printf("Name = %s, index = %d, return from float function = %f\n", ptr->name,
ptr->index, ptr->foo());
}
struct R1 *newlist(int i) {
struct R1 *newfoo;
newfoo = malloc(sizeof(struct R1));
if (newfoo) {
printf("List name: "
newfoo->name = malloc(30);
scanf("%s", newfoo->name);
newfoo->index = i + 1;
newfoo->foo = bogus;
newfoo->next= NULL;
}
return newfoo;
}
Say I want to keep track of the order in this list using the index member, how would you go about iterating through the index members? This is not urgent or anything, I'm just
curious. Also, is there a memory leak there with not releasing newfoo->name?
#include <stdio.h>
#include <stdlib.h>
struct R1 {
char *name;
int index;
float (*foo)(void);
struct R1 *next;
};
float bogus(void);
void PrintList(struct R1 *ptr);
struct R1 *newlist(int i);
int main(void) {
struct R1 foobar = { "mytest", 0, bogus, NULL};
foobar.next = newlist(foobar.index);
PrintList(&foobar);
PrintList(foobar.next);
free(foobar.next);
return 0;
}
float bogus(void) {
return rand() % 6;
}
void PrintList(struct R1 *ptr) {
printf("Name = %s, index = %d, return from float function = %f\n", ptr->name,
ptr->index, ptr->foo());
}
struct R1 *newlist(int i) {
struct R1 *newfoo;
newfoo = malloc(sizeof(struct R1));
if (newfoo) {
printf("List name: "
newfoo->name = malloc(30);
scanf("%s", newfoo->name);
newfoo->index = i + 1;
newfoo->foo = bogus;
newfoo->next= NULL;
}
return newfoo;
}
Say I want to keep track of the order in this list using the index member, how would you go about iterating through the index members? This is not urgent or anything, I'm just
curious. Also, is there a memory leak there with not releasing newfoo->name?