0

Hi have a problem, this code should read a file and then save it in a linked list, just the <uid><name> from a lie looking like: <username>:<password>:<uid>:<gid>:<fullname>:<home dir>:<shell>

I can't find the segmentation fault error atm, but hints on the code would be helpfull.

Atfer the insert in user list the info should be sorted to the sortUser, with the smalest int first <uid>.

#include<stdio.h>
#include<stdlib.h>

int main(int argc, char *argv[]){

	FILE *file;
	char line [ 128 ], x;
	int y;
	unsigned int tmpUid;
	void* tmpName;

	file=(fopen(argv[1],"r"));	

	printf("make node and stortNode");

	struct node {
		unsigned int uid;
		char* name;
		struct node* next;
	} user, *p, sortUser, *sp;

	
	printf("using malloc for nodes");

	p = malloc(sizeof(struct node));
	sp = malloc(sizeof(struct node));

	printf("checking if file is empty");

	if(file != NULL){

		printf("starting the read loop");

		while( fgets ( line, 128, file ) != NULL ){
			printf("first-loop");
			char str[10];
			y=0;

			while(x!='\n'){

				printf("second-loop");

				int i;
				int size;

				x=fgetc(file);

				if(x==':')
					y++;

				if(y=0){
					size++;
					realloc(user.name,(sizeof(struct node)) + size);
					user.name=&x;
				}

				if(y=2){
					x=str[i];
					i++;    
				}
			}

			user.uid=atoi(str);
			p=p->next;
			p->next = NULL;
		}

		while(sp!=NULL){
			printf("trying to sort!");
			if(sp->uid < p->uid){

				sp->uid = p->uid;
				sp++;
			}
			p++;
		}

	}

	free(p);
	free(sp);

	return 0;
}
2
Contributors
1
Reply
2
Views
8 Years
Discussion Span
Last Post by ArkM
0

It seems you don't understand basics of dynamic memory allocation:
1. struct node has char*name member (pointer to char) but you don't allocate memory for name object. So you have garbage pointer values in uninitialized structures. Use malloc to allocate memory and save pointers to these structure members for all struc node variables.
2. realloc() returns a NEW pointer for reallocated memory. You must save it then reuse. Now you lost this new pointer and continue to work with invalid (old) pointer value.
3. It seems your list building method is incorrect. Take a pencil and a sheet of paper and try to check the algorithm step by step.
4. Test if (file == NULL) is not "checking if file is empty": fopen returns 0 if it can't open the file! Test file immediately after opening and stop processing if nothing to do.

Resolve #1, #2 and #3 points then come back...

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.