Hello,
I was just trying to write some simple codes to learn C. I wrote 3 functions, create a list,print a list and free a list.
but i get segfault while printing the list. (by the way, list is not a list datastructure. it's just an array)
In create_list, I get memory blocks dynamicaly so why does it complain in print_list function?
here the code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define N 1
struct A
{
int x;
char* str;
};
int create_list(struct A* list);
void print_list(struct A* list);
void free_list(struct A* list);
int main(int argc, char** argv)
{
struct A* list;
create_list(list);
print_list(list);
free_list(list);
}
int create_list(struct A* list)
{
int i = 0;
list = (struct A*) malloc(N*sizeof(struct A));
char buf[100];
for (i=0;i<N;i++)
{
list[i].x=i;
sprintf(buf, "%s%d", "element", i);
list[i].str = strdup(buf);
}
}
void print_list(struct A* list)
{
int i = 0;
for (i=0; i<N; i++)
{
printf("element %d, x:%d str:%s\n", i, list[i].x, list[i].str);
}
}
void free_list(struct A* list)
{
int i = 0;
for (i=0; i<N; i++)
{
free(list[i].str);
}
free(list);
list=NULL;
}