473,657 Members | 2,283 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Allocating memory for strings

Hi All,
somebody told me this morning that the following is leagal.

char *a = "Hello wrold";

The memory is automatically allocated on the fly. Is this correct?

Oct 6 '07 #1
20 1971
Win Sock wrote:
Hi All,
somebody told me this morning that the following is leagal.

char *a = "Hello wrold";

The memory is automatically allocated on the fly. Is this correct?
The storage for the string is set aside during translation and the
pointer 'a' is set to point to it's beginning.

If the pointer is not static and no other pointers point to the string,
then the string becomes irretrievable when 'a' goes out of scope.

Oct 6 '07 #2
On Oct 6, 6:45 pm, Win Sock <nos...@nospam. comwrote:
Hi All,
somebody told me this morning that the following is leagal.

char *a = "Hello wrold";

The memory is automatically allocated on the fly. Is this correct?
No.

A string literal like "Hello wrold" works exactly as if you had a
static array of const char, and got a pointer to that array, cast to
char* instead of const char*. So

char *a = "Hello wrold";

works exactly the same as

const char secret_array [] = "Hello wrold";
char *a = (char *) secret_array;

Oct 6 '07 #3
Win Sock wrote:
Hi All,
somebody told me this morning that the following is leagal.

char *a = "Hello wrold";

The memory is automatically allocated on the fly. Is this correct?
Not in the sense of malloc() and friends. free(a) is Undefined. The
constant string "Hello wrold" is placed somewhere in memory as an
anonymous array of char, the address of which is placed in a.

Spelling? legal and world.

--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Oct 6 '07 #4
"christian. bau" <ch***********@ cbau.wanadoo.co .ukwrites:
char *a = "Hello wrold";

works exactly the same as

const char secret_array [] = "Hello wrold";
char *a = (char *) secret_array;
If it's outside any function, yet; otherwise, secret_array must
be declared static.
--
"For those who want to translate C to Pascal, it may be that a lobotomy
serves your needs better." --M. Ambuhl

"Here are the steps to create a C-to-Turbo-Pascal translator..." --H. Schildt
Oct 6 '07 #5
"christian. bau" <ch***********@ cbau.wanadoo.co .ukwrites:
On Oct 6, 6:45 pm, Win Sock <nos...@nospam. comwrote:
>somebody told me this morning that the following is leagal.

char *a = "Hello wrold";

The memory is automatically allocated on the fly. Is this correct?

No.

A string literal like "Hello wrold" works exactly as if you had a
static array of const char, and got a pointer to that array, cast to
char* instead of const char*. So

char *a = "Hello wrold";

works exactly the same as

const char secret_array [] = "Hello wrold";
char *a = (char *) secret_array;
Except that string literals aren't const. (Attempting to modify a
string literal invokes undefined behavior, but only because the
standard explicitly says so.) It would be better if string literals
*were* const, but that would have broken existing code back in 1989
when the ANSI standard first introduced the "const" keyword.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Oct 6 '07 #6
Win Sock wrote:
Hi All,
somebody told me this morning that the following is leagal.

char *a = "Hello wrold";

The memory is automatically allocated on the fly. Is this correct?
String literals may be placed in read-only memory, and it's undefined
behavior (UB) altering what *a points to. Hence, you should rather use:

const char *a = "Hello wrold";

Note that, else the compiler might not catch this error:

$ cat -n main.c
1 #include <stdio.h>
2
3
4 int main(void)
5 {
6 char *a = "Hello";
7 const char *b = "Hello";
8
9 printf("%s %s\n", a, b);
10
11 a[0]='\0';
12 b[0]='\0';
13
14 return 0;
15 }

$ gcc -ansi -pedantic -W -Wall main.c
main.c: In function âmainâ:
main.c:12: error: assignment of read-only location

above, there was no warning about the UB at line 11!

--
Tor <torust [at] online [dot] no>

"There are two ways of constructing a software design. One way is to
make it so simple that there are obviously no deficiencies. And the
other way is to make it so complicated that there are no obvious
deficiencies"
Oct 6 '07 #7
Tor Rustad wrote:
Win Sock wrote:
>Hi All,
somebody told me this morning that the following is leagal.

char *a = "Hello wrold";

The memory is automatically allocated on the fly. Is this correct?

String literals may be placed in read-only memory, and it's undefined
behavior (UB) altering what *a points to. Hence, you should rather
use:

const char *a = "Hello wrold";

Note that, else the compiler might not catch this error:

$ cat -n main.c
1 #include <stdio.h>
2
3
4 int main(void)
5 {
6 char *a = "Hello";
7 const char *b = "Hello";
8
9 printf("%s %s\n", a, b);
10
11 a[0]='\0';
12 b[0]='\0';
13
14 return 0;
15 }

$ gcc -ansi -pedantic -W -Wall main.c
main.c: In function âmainâ:
main.c:12: error: assignment of read-only location

above, there was no warning about the UB at line 11!
Interestingly if the const qualifier is removed, compilation succeeds
under gcc, but the executable terminates with a segmentation fault.
This indicates that gcc places the strings in read-only storage.

On the other hand under the lcc-linux32 compiler nothing unexpected
happens. Apparently string literals are _not_ placed into read-only
storage by lcc-linux32.

Oct 6 '07 #8
Keith Thompson <ks***@mib.orgw rites:
"christian. bau" <ch***********@ cbau.wanadoo.co .ukwrites:
> char *a = "Hello wrold";

works exactly the same as

const char secret_array [] = "Hello wrold";
char *a = (char *) secret_array;

Except that string literals aren't const. (Attempting to modify a
string literal invokes undefined behavior, but only because the
standard explicitly says so.)
I think that's why Christian included the cast to char *. With
the cast, the effect is the same.
--
char a[]="\n .CJacehknorstu" ;int putchar(int);in t main(void){unsi gned long b[]
={0x67dffdff,0x 9aa9aa6a,0xa77f fda9,0x7da6aa6a ,0xa67f6aaa,0xa a9aa9f6,0x11f6} ,*p
=b,i=24;for(;p+ =!*p;*p/=4)switch(0[p]&3)case 0:{return 0;for(p--;i--;i--)case+
2:{i++;if(i)bre ak;else default:continu e;if(0)case 1:putchar(a[i&15]);break;}}}
Oct 6 '07 #9
santosh wrote:

[...]
Interestingly if the const qualifier is removed, compilation succeeds
under gcc, but the executable terminates with a segmentation fault.
This indicates that gcc places the strings in read-only storage.
Yes.
On the other hand under the lcc-linux32 compiler nothing unexpected
happens. Apparently string literals are _not_ placed into read-only
storage by lcc-linux32.
Did you get a warning with lcc-linux32? I don't have the lcc-linux32
compiler, but it could use the same storage location for those two
string literals, which I purpose used "Hello" for both.

So something "unexpected " could still happen.

Note that splint issue two warnings for the sample code i posted.

--
Tor <torust [at] online [dot] no>

"There are two ways of constructing a software design. One way is to
make it so simple that there are obviously no deficiencies. And the
other way is to make it so complicated that there are no obvious
deficiencies"
Oct 6 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
4120
by: soni29 | last post by:
hi, i'm reading a c++ book and noticed that the author seems to allocate memory differently when using classes, he writes: (assuming a class called CBox exists, with member function size()): // first way CBox x; x.size(); // second way
4
745
by: Sameer | last post by:
Hello Group, This is one problem in programming that is troubling me. there is a segmentation fault just before creating memory to a structure ..i.e, just after the "allocating memory " statement. This happens for some inputs and not all. What can be the reason for such fault ?
5
3666
by: Johnathan Doe | last post by:
Why is is necessary to write a function that allocates memory for, or changes, a pointer to a char array using char** instead of char*? E.g. void modify_string( char** string ) { if( string == NULL ) return;
7
2095
by: boss_bhat | last post by:
Hi all , I am beginner to C programming. I have a defined astructure like the following, and i am using aliases for the different data types in the structure, typedef struct _NAME_INFO { struct _NAME_INFO *Next; ULONG LastId; ULONG Id; PVOID Value;
3
5041
by: Tod Birdsall | last post by:
Hi All, The organization I am working for has created a new corporate website that used Microsoft's Pet Shop website as their coding model, and dynamically served up content, but cached each page by content ID. The site appears to be working well. It is hosted on a Windows 2003 server with 2 Gigs of RAM. It was built using Visual Studio .NET 2005 and us running under the .NET Framework 2.0 Beta The Issue :
19
3800
by: allanallansson | last post by:
Hi i would like some guidelines for a experiment of mine. I want to experiment with the swap and ctrl-z in linux. And for this i want to create a c program that allocates almost all the free memory resources. So far i have tried to use #include <stdio.h> int main() { int *ip;
20
2078
by: Neclepsio | last post by:
Hi everyone. I've made a class Matrix, which contains a pointer to the data and some methods which all return a copy of the matrix modified in some way. The program works quite well for small matrices, but as matrix dimension grows up it crashes in deterministic locations depending on data, machine and OS. In particular, this happens when I test it with 3000x3000 matrices (which take up more than 30MB) under three different machines/OSes....
4
2973
by: Rakesh Kumar | last post by:
Hi All - In a project of mine - I was trying to scale down the actual issue to the following piece of code. I need to allocate an array of strings and reserve the individual string to a particular size (4K) . I wrote 2 functions - allocVectorOfStrings() and allocArrayOfStrings(). Each of them seem to allocate similar amounts of memory - but the version of vectorOfStrings seem to crash with the following error - "double free or corruption...
10
1760
by: Chris Saunders | last post by:
Here is the declaration of a struct from WinIoCtl.h: // // Structures for FSCTL_TXFS_READ_BACKUP_INFORMATION // typedef struct _TXFS_READ_BACKUP_INFORMATION_OUT { union { //
0
8323
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8838
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8513
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7351
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5638
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4173
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2740
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1969
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1732
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.