Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.c > #162723

Re: Segmentation fault when appending to a Linked List

From Lew Pitcher <lew.pitcher@digitalfreehold.ca>
Newsgroups comp.lang.c
Subject Re: Segmentation fault when appending to a Linked List
Date 2021-09-10 21:45 +0000
Organization A noiseless patient Spider
Message-ID <shgjll$6um$3@dont-email.me> (permalink)
References <447bf689-7913-478b-8c7e-5519192552a6n@googlegroups.com>

Show all headers | View raw


Regarding the error reported by gdb

On Fri, 10 Sep 2021 13:51:26 -0700, Bithov Vinu Student wrote:

> Here is my code for parsing S-expressions:
> 
> ```
> #include <stdio.h>
> #include <stdlib.h>
> #include <string.h>
> #define TOKEN_MAX 256
> typedef struct List List;
> 
> struct List {
> 	union {
> 		char* string;
> 		List* list;
> 	};
> 	enum {
> 		STRING,
> 		SYMBOL,
> 		LIST
> 	} type;
> 	List* next;
> };
> 
> List* parse(FILE* stream) {
> 	List* head, *tail = NULL;
> 	char c;
> 
> 	while((c = fgetc(stream)) != EOF) {
> 		List* current = NULL;
> 
[snip]
> 		if(current != NULL) {
> 			if(head == NULL) {
> 				head = tail = current;
> 			} else {
> 				tail = tail->next = current;
> 			}
> 		}
> 	}
> 	return head;
> }
[snip]
> Compiling with gcc with standard flags gives me a segfault. Compiling with -g and using "gdb run" gives me the output:
> 
> ```
> Starting program: /home/USER/sex 
> 
> Program received signal SIGSEGV, Segmentation fault.
> 0x00005555555553e8 in parse (stream=0x5555555592a0) at sex.c:57
> 57					tail = tail->next = current;
> ```
> 
> What have I done wrong? Thanks

Note your initialization...
> 	List* head, *tail = NULL;

Note the assignment
> 				tail = tail->next = current;

Given the initialization of tail,
1) Where do you set tail to an object (other than NULL)?
2) what does tail point at?
3) what does tail->next reference?

-- 
Lew Pitcher
"In Skills, We Trust"

Back to comp.lang.c | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Segmentation fault when appending to a Linked List Bithov Vinu Student <vinub@calday.co.uk> - 2021-09-10 13:51 -0700
  Re: Segmentation fault when appending to a Linked List Lew Pitcher <lew.pitcher@digitalfreehold.ca> - 2021-09-10 20:57 +0000
  Re: Segmentation fault when appending to a Linked List Lew Pitcher <lew.pitcher@digitalfreehold.ca> - 2021-09-10 21:45 +0000
  Re: Segmentation fault when appending to a Linked List Ben Bacarisse <ben.usenet@bsb.me.uk> - 2021-09-10 23:28 +0100

csiph-web