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 15:18:00 -0700 Organization: None to speak of Lines: 50 Message-ID: References: <89549322-236e-4a59-9bb5-dc881593a846@googlegroups.com> <7e5f00ae-7843-42e8-9335-c46e1959244c@googlegroups.com> <1b1stnc1vj.fsf@pfeifferfamily.net> <1bshm3akop.fsf@pfeifferfamily.net> 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/8nH31IAY6ImBeIH/dhdGM" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux) Cancel-Lock: sha1:zVtIHAmf7RB6j5M4DsBKDOYDdW4= sha1:7cDMk9HQKwR5SppeP5SrsLW2U4A= Xref: csiph.com comp.lang.c:106855 Jorgen Grahn writes: > On Thu, 2017-03-23, Jerry Stuckle wrote: [...] >> It is also recommended by the SEI CERT C Coding Standard at >> https://www.securecoding.cert.org/confluence/display/c/SEI+CERT+C+Coding+Standard >> >> See recommendation MEM02-C (Memory Management): >> https://www.securecoding.cert.org/confluence/display/c/MEM02-C.+Immediately+cast+the+result+of+a+memory+allocation+function+call+into+a+pointer+to+the+allocated+type >> > But they seem to nullify it all in the end with: > > "MEM02-C-EX1: Do not immediately cast the results of malloc() for code > that will be compiled using a C90-conforming compiler [...]|" > > Am I misinterpreting, or do they really say "ignore this advice unless > your compiler is more than thirty years old"? Yes, I think that's what they mean. C90 lets you call a function with no visible declaration, but it assumes that the function returns int. If you omit the required `#include `, then a call without a cast: int *p = malloc(sizeof *p); will cause a diagnostic (assigning an int value to an int* object), but a call with a cast: int *p = (int*)malloc(sizeof *p); likely will not. But the cast will convert the nonexistent int result to int*, causing undefined behavior. In C99 and later, you don't have that particular problem, since omitting `#include ` should trigger a diagnostic with or without the cast. The exception makes sense *if* you think the cast is a good idea. But if you omit the cast in all cases, you'll have more robust code that compiles without complaint in C90, C99, or C11. (Pre-ANSI compilers might complain, but presumably they're rarely an issue.) [...] -- 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"