passing a pointer to string giving segmentaion fault

This is a discussion on passing a pointer to string giving segmentaion fault within the C Programming forums, part of the General Programming Boards category; Code: #include "stdio.h" void fun(char *pa) { strcpy(pa,"MyString"); } int main() { //char *a="hello"; // case 1 char a[5]="hello"; // ...

  1. #1
    Registered User
    Join Date
    Mar 2008
    Location
    New York
    Posts
    24

    passing a pointer to string giving segmentaion fault

    Code:
    #include "stdio.h"
    
    void fun(char *pa)
    {
    	strcpy(pa,"MyString");
    	
    }
    
    int main()
    {
    	//char *a="hello"; // case 1
    	char a[5]="hello"; // case 2
    	fun(a);
    	printf("%s",a);
    	return 0;
    }

    In the above code, case 2 gives the output "MyString" its ok.but why is case 1 giving segmentation fault?

    Thanks and Regards,
    Alxpo

  2. #2
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,831
    Because "MyString" has 9 characters including the trailing nul, so array a[5] gets overfilled.

  3. #3
    Technical Lead QuantumPete's Avatar
    Join Date
    Aug 2007
    Location
    London, UK
    Posts
    894
    Quote Originally Posted by nonoob View Post
    Because "MyString" has 9 characters including the trailing nul, so array a[5] gets overfilled.
    Yes, but that's case 2, which doesn't crash. That's because, although you're writing into memory you don't own, there's nothing there that the system currently needs. So while it's not safe, it probably won't crash.
    Case 1 will definitly crash, because you're writing to a write-protected area of memory. All string literals (anything in quotation marks) resides in a special area of memory. You can get a pointer to it (as you have done), but trying to write to that area will cause you do crash.

    QuantumPete
    "No-one else has reported this problem, you're either crazy or a liar" - Dogbert Technical Support
    "Have you tried turning it off and on again?" - The IT Crowd

  4. #4
    Registered User
    Join Date
    Mar 2008
    Location
    New York
    Posts
    24
    Thanks QuantumPete,

    Would you please name the special area of memory(if it having).Its an area in memory (from code segment or from data segment ) where all constant data are stored, right?
    Correct me if I am wrong.

    Thanks Again,
    --Alxpo
    Last edited by Alexpo; 10-03-2008 at 06:42 AM.

  5. #5
    Technical Lead QuantumPete's Avatar
    Join Date
    Aug 2007
    Location
    London, UK
    Posts
    894
    Yes, it's stored in the .data section of your program.

    QuantumPete
    "No-one else has reported this problem, you're either crazy or a liar" - Dogbert Technical Support
    "Have you tried turning it off and on again?" - The IT Crowd

  6. #6
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,437
    "Hello" is actually 6 characters (including the \0), so you'll still get undefined behavior if you try to print your array with it.
    Remember that each string needs the amount of characters you need to store + 1 for the \0 char.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  7. #7
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,831
    True... the compiler should have caught it as an "array bounds overflow". At least mine does.

  8. #8
    Registered User
    Join Date
    Jul 2008
    Posts
    37
    Quote Originally Posted by Alexpo View Post
    Code:
    void fun(char *pa)
    {
    	strcpy(pa,"MyString");
    	
    }
    here the problem is, you are copying the string "MyString" to an address having unknown size of memory space. you should either allocate a memory for *pa of size equal to sizeof("MyString")+1( for null char) using malloc() function or make the formal argument an array of size 9.
    after altering your code in this way, everything will be fine.

    you should know the difference between char string[] and char *ptrstr, the former is simply an array and have a fixed memory space but later one is simply a pointer. and both are different things.

    and one more thing, there is not any bound checking for arrays in C/C++. hence, you can assign a string to an string array more than its size which will be overwritten to its allocated space.
    Last edited by san_crazy; 10-03-2008 at 10:38 PM.

  9. #9
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,451
    > you should know the difference between char string[] and char *ptrstr, the former is simply an array and have a fixed memory space but later one is simply a pointer.
    > and both are different things.
    True, if you're declaring data.
    char string[] = "foo";
    char *string = "foo";

    are indeed different things.

    But as arguments in a function prototype or definition, they're equivalent.
    void foo ( char *string );
    void foo ( char string[] );
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  10. #10
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,437
    Quote Originally Posted by nonoob View Post
    True... the compiler should have caught it as an "array bounds overflow". At least mine does.
    Unfortunately, it's legal in C.
    What it does is will the array with { 'H, 'e', 'l', 'l', 'o' } (notice the missing '\0'). This is illegal in C++ and such a compiler will indeed complain.

    Quote Originally Posted by san_crazy View Post
    here the problem is, you are copying the string "MyString" to an address having unknown size of memory space. you should either allocate a memory for *pa of size equal to sizeof("MyString")+1( for null char) using malloc() function or make the formal argument an array of size 9.
    after altering your code in this way, everything will be fine.
    Actually, I believe sizeof("something") will return the size of the string + the '\0', because it is considered part of a string (but strlen("something") will return only the length of the actual string, excluding the '\0').
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  11. #11
    Registered User
    Join Date
    Jul 2008
    Posts
    37
    Quote Originally Posted by Elysia View Post

    Actually, I believe sizeof("something") will return the size of the string + the '\0', because it is considered part of a string (but strlen("something") will return only the length of the actual string, excluding the '\0').
    I didn't mean the keyword sizeof() by using the same name indeed, it was just an example.

  12. #12
    Registered User
    Join Date
    Mar 2008
    Location
    New York
    Posts
    24
    Hi San_Crazy & all,

    void fun(char *pa)
    {
    strcpy(pa,"MyString");

    }

    here the problem is, you are copying the string "MyString" to an address having unknown size of memory space
    .

    Its true that we don't know the size of memory pointed by "pa" but the folloing code is also woking fine

    Code:
    void fun(char *pa)
    {
    	pa="Mystring";
    	
    }
    I mean to say, while assigning to pa ,pa's size is unknown to us.But how is it working but in case of strcpy its not.Please, explain.

  13. #13
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,437
    This doesn't work. That's because the pointer itself is passed by value. You're just assigning a new address to the local copy of the pointer, so you won't see the "new" string when the function terminates.
    Your original problem is that you copied a too large string into a too small buffer. You didn't know its size and overwrote stuff you shouldn't have.

    Also remember: string literals are const. Do not assign them to non-constant pointers.
    And don't use pointers without allocating them (another thing you did in your first post).
    http://cpwiki.sourceforge.net/Common...kes_and_errors
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  14. #14
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by Alexpo View Post
    Thanks QuantumPete,

    Would you please name the special area of memory(if it having).Its an area in memory (from code segment or from data segment ) where all constant data are stored, right?
    Correct me if I am wrong.

    Thanks Again,
    --Alxpo
    Modern OS's support multiple parts of data sections, some of which cane be read-only, so when your application tries to write to this part of the data section, then it will produce a page-fault for "write to non-writable memory".

    In older compilers, string literals got stored in the read-only code segment.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  15. #15
    Registered User
    Join Date
    Mar 2008
    Location
    New York
    Posts
    24
    Hi Elysia,

    Got the point.Thanks.

    Hi Mats,

    In older compilers, string literals got stored in the read-only code segment.
    Thanks for this info. beacuse I was confused it to be data or code section.As somewhere I read it as code section and some where as data section.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problems passing a file pointer to functions
    By smitchell in forum C Programming
    Replies: 4
    Last Post: 09-30-2008, 02:29 PM
  2. OOP Question DB Access Wrapper Classes
    By digioz in forum C# Programming
    Replies: 2
    Last Post: 09-07-2008, 04:30 PM
  3. Inheritance Hierarchy for a Package class
    By twickre in forum C++ Programming
    Replies: 7
    Last Post: 12-08-2007, 03:13 PM
  4. Problem with passing back pointer pointed to string
    By whichet in forum C Programming
    Replies: 9
    Last Post: 11-21-2007, 06:55 AM
  5. Locating A Segmentation Fault
    By Stack Overflow in forum C Programming
    Replies: 12
    Last Post: 12-14-2004, 12:33 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21