DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 2 of 2

Thread: Static allocation vs allocation on stack

  1. #1
    Join Date
    Jan 2008
    Posts
    1

    Static allocation vs allocation on stack

    This code willl give segmentation fault :
    #include <iostream>

    int main()
    {
    char* ptr = "abc d ef g"; //static allocation

    for(int i = 0; i<strlen(ptr); ++i)
    {
    if(ptr[i] == ' ')
    {
    for(int j = i; j<strlen(ptr); ++j)
    ptr[j] = ptr[j+1];
    }
    }

    std::cout<<"output="<<ptr;
    return 0;
    }


    but this won't :
    #include <iostream>

    int main()
    {
    char ptr[30] = "abc d ef g"; //allocated on stack

    for(int i = 0; i<strlen(ptr); ++i)
    {
    if(ptr[i] == ' ')
    {
    for(int j = i; j<strlen(ptr); ++j)
    ptr[j] = ptr[j+1];
    }
    }

    std::cout<<"output="<<ptr;
    return 0;
    }

  2. #2
    Join Date
    Nov 2003
    Posts
    4,118
    Your first code listing has a bug. You're using a non const char * which is initialized with a constant literal string. It's no wonder then that when you try to modify that "string" you're getting a crash.
    Remember: pointers are not arrays. A pointer doesn't contain the memory of the object it's pointing to, as opposed to an array.
    Secondly, the difference here is not really between pointers and aeeays but rather between const data and non-const data:

    char ptr[30] = "abc d ef g"; //ptr is an array of 30 non-const char

    which is why you can modify the elements of that array safely.
    Danny Kalev

Similar Threads

  1. TicTacToe help...
    By MP35719 in forum Java
    Replies: 0
    Last Post: 12-16-2006, 07:06 PM
  2. KeyListener not responding
    By lordanki in forum Java
    Replies: 3
    Last Post: 04-04-2006, 10:13 AM
  3. Queue Stack Question
    By trixma in forum Java
    Replies: 4
    Last Post: 08-14-2005, 01:03 PM
  4. Trouble buffering transparent gif
    By axlan in forum Java
    Replies: 2
    Last Post: 06-22-2005, 08:21 AM
  5. Interface leaks in C#?
    By Kevin Burton in forum .NET
    Replies: 12
    Last Post: 10-09-2000, 10:29 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center