Path: csiph.com!eternal-september.org!feeder.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Keith Thompson Newsgroups: comp.lang.c Subject: Re: My C program does not compile or gives segmentation fault Date: Thu, 23 Mar 2017 11:48:04 -0700 Organization: None to speak of Lines: 56 Message-ID: References: <89549322-236e-4a59-9bb5-dc881593a846@googlegroups.com> <7e5f00ae-7843-42e8-9335-c46e1959244c@googlegroups.com> <1b60izc23w.fsf@pfeifferfamily.net> <08f2d23e-4308-4676-8d1b-52f93f2fd6df@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: mx02.eternal-september.org; posting-host="1b33b319c9f9fcfff45ec1f5b5f6ee2d"; logging-data="28253"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/+inHapJXanLRx4WfGUbFk" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux) Cancel-Lock: sha1:g9M/WLxC49fpjnDt5f8uSIkdE4g= sha1:2Tff5n3C1FrtSDZywY4CeCwxJys= Xref: csiph.com comp.lang.c:106834 acidlategamer@gmail.com writes: > On Thursday, March 23, 2017 at 11:34:09 PM UTC+5:30, acidla...@gmail.com wrote: >> On Thursday, March 23, 2017 at 11:22:28 PM UTC+5:30, Joe Pfeiffer wrote: >> > acidlategamer@gmail.com writes: >> > > >> > > I see example codes where q is never initialised to NULL and a >> > > function is there that says 'createq'. All it do in the function is >> > > just make rear and front to point to NULL. At that moment nothing is >> > > allocated to anyone. >> > >> > Either you're misunderstanding the examples, or they are wrong. Do you >> > have a URL? >> >> I am reading a book. I have formatted and removed extra code for better readability. >> >> http://codepad.org/4IiDVzpT >> >> Thanks for your replies. > > Book name is data structures using C - Reema Thareja Either the "extra code" was necessary for correctness, or the code in the book is incorrect. At file scope, you have: struct queue *q;//Here q is not initialized q is not *explicitly* initialized. It's implicitly initialized to NULL. Any file-scope and/or static object without an initializer is implicitly initialized to zero; for a pointer object, that's a null pointer. int main() { int val, option; create_queue(q);//just called create queue. At this moment nothing such as struct node is created At this point, q still has its initial null value, so the call is equivalent to create_queue(NULL). Since function arguments are always passed by value, this cannot change the value of q. void create_queue(struct queue *q) { q -> rear = NULL;//how this happened without any error?? q -> front = NULL; } This dereferences a null pointer, causing undefined behavior. You were lucky enough to get a segmentation fault, a clear indication that there's a problem. -- Keith Thompson (The_Other_Keith) kst-u@mib.org Working, but not speaking, for JetHead Development, Inc. "We must do something. This is something. Therefore, we must do this." -- Antony Jay and Jonathan Lynn, "Yes Minister"