Results 1 to 6 of 6
Hi,
Just wanted to know the consequences if I write this piece of a code in C.
int main()
{
char* s1 = "abcdefghijklmnopqrstuvwxyz";
char* s2 = (char*) malloc (100);
...
- 02-24-2010 #1Just Joined!
- Join Date
- Oct 2008
- Posts
- 13
usage of strings in C
Hi,
Just wanted to know the consequences if I write this piece of a code in C.
int main()
{
char* s1 = "abcdefghijklmnopqrstuvwxyz";
char* s2 = (char*) malloc (100);
strcpy(s2,"Alphabets:");
strcat(s2,s1);
strcat(s2," ");
strcat(s2,s1);
printf("s1 is %s and s2 is %s",s1,s2);
free(s2);
return 0;
}
Where does s1 point to?
Assume that my environment is having less memory.
Thanks and Regards,
krishna
- 02-24-2010 #2
String s1 - char* s1 = "abcdefghijklmnopqrstuvwxyz";
points to the const string "abcdefghijklmnopqrstuvwxyz".Make mine Arch Linux
- 02-24-2010 #3Just Joined!
- Join Date
- Oct 2008
- Posts
- 13
so, where will be the memory allocated? In the code segment?
- 02-24-2010 #4
Maybe this example will clarify some of your questions:
Code:#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char* s1 = "abcdefghijklmnopqrstuvwxyz"; char* s2 = (char*) malloc (100); fprintf(stdout, "s1->%p\n", (void*)&s1[0]); fprintf(stdout, "s2->%p\n", (void*)&s2[0]); strcpy(s2,"Alphabets:"); strcat(s2,s1); strcat(s2," "); strcat(s2,s1); fprintf(stdout, "s1->%p\n", (void*)&s1[0]); fprintf(stdout, "s2->%p\n", (void*)&s2[0]); printf("s1 is %s and s2 is %s",s1,s2); free(s2); return 0; }Make mine Arch Linux
- 02-24-2010 #5Debian GNU/Linux -- You know you want it.
- 02-24-2010 #6
On the standard Linux architecture, your s1 string gets allocated at compile time (it's a constant!), so it is located in the read-only data segment of memory. This is why in the following code:
s1 and s2 are actually the same pointer.Code:char *s1 = "hello"; char *s2 = "hello";
On the other hand, when you invoke malloc, memory is allocated on the heap, which is a read-writable section of memory.Code:bricka@joust ~/test/c $ cat pointers_equal.c #include <stdio.h> int main() { char *s1 = "hello"; char *s2 = "hello"; printf("s1 = %p, s2 = %p\n", s1, s2); return 0; } bricka@joust ~/test/c $ ./a.out s1 = 0x80484f0, s2 = 0x80484f0DISTRO=Arch
Registered Linux User #388732


Reply With Quote
