Path: csiph.com!eternal-september.org!feeder.eternal-september.org!reader01.eternal-september.org!.POSTED!not-for-mail From: Keith Thompson Newsgroups: comp.lang.c Subject: Re: does char *str="abcd"; alloc addressable memory? Date: Mon, 06 Jul 2020 23:25:20 -0700 Organization: None to speak of Lines: 40 Message-ID: <873663c04v.fsf@nosuchdomain.example.com> References: <87k0zgbiwt.fsf@nosuchdomain.example.com> Mime-Version: 1.0 Content-Type: text/plain Injection-Info: reader02.eternal-september.org; posting-host="54f4879226d9f3933c68a92aeca604f0"; logging-data="8510"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+spUVwXWBOIBeGfXq0ayIv" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/26.3 (gnu/linux) Cancel-Lock: sha1:xYLqfLbyc7LB5s3JmvRpXQHKXsw= sha1:eE4jdvWKjvLBS/kstH3+rUf6g9E= Xref: csiph.com comp.lang.c:153097 John Forkosh writes: > Keith Thompson wrote: >> >> Some compilers have non-conforming options to treat string literals as >> const. (gcc has "-Wwrite-strings".) > > Wasn't aware of that warning, and sure enough... > bash-5.0$ cc -Wwrite-strings tester.c -o tester > tester.c: In function 'main': > tester.c:7:15: warning: initialization discards 'const' qualifier > from pointer target type [-Wdiscarded-qualifiers] > 7 | char *str = ( argc>1? argv[1] : "01234&56789" ); > | ^ > And (as suggested downthread) changing line 7 to > char *str = ( argc>1? argv[1] : (char *)"01234&56789" ); > eliminates the warning, but the program still segfaults. > > So, the really nice -switch would be one that reverts to the > classical behavior where "string literals" aren't const. > Any way to do that? I'm not aware of any such option. If you really want a writable copy of a string literal, you might consider strdup(), which uses malloc() to create a copy of its argument string. It's not C standard (though I think it's being added in the next standard), but it is defined by POSIX -- and it's easy enough to write your own version. Or just create a writable array object: char my_string[] = "01234&56789"; I really wouldn't advise trying to modify the string literal itself, even if you can find a compiler that lets you get away with it. -- Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.com Working, but not speaking, for Philips Healthcare void Void(void) { Void(); } /* The recursive call of the void */