Thread: Seg Fault in function. HELP!

  1. #1
    Registered User
    Join Date
    Sep 2006
    Posts
    51

    Seg Fault in function. HELP!

    Hi,

    I'm writing a function to output the substring of a given string with its start and end index. But i seem to be getting seg faults with this. Can anyone help me, plz!

    here's my code:
    Code:
    char *substring(char *s, int start, int end){
    	int i;
    	char *x; 
    
    	for(i=start; i<=end; i++){
    		x[i] = s[i];
    	}
    	return x;
    	
    }
    Where 's' is the given string, and 'x' is the desired substr output.... start & end are the string indices.

    THX!

  2. #2
    Devil's Advocate SlyMaelstrom's Avatar
    Join Date
    May 2004
    Location
    Out of scope
    Posts
    4,079
    That pointer isn't allocated... you have no idea where it's pointing, yet you try to assign to it. That's a problem with most operating systems.
    Code:
    char *x = malloc(sizeof(char) * (end - start) + 1);  // Plus one for the '\0'
    // ...and at this point you'd also have to edit your for loop since your x string 
    // won't have the same indices as your s string
    Last edited by SlyMaelstrom; 09-27-2006 at 09:47 PM. Reason: Whoops... forgot my order of operations
    Sent from my iPadŽ

  3. #3
    Registered User
    Join Date
    Sep 2006
    Posts
    51
    Gosh!...it works now!!! hahaha

    Thanks so much....

    At least i've just learnt a new thing!
    Man, i suck at pointers...

  4. #4
    Devil's Advocate SlyMaelstrom's Avatar
    Join Date
    May 2004
    Location
    Out of scope
    Posts
    4,079
    Actually, you should really allocate an extra char for your x string and tack on a NULL character at the end since that's needed for it to really be a string. Had I rewrote your whole code, I would have considered that, but I didn't want to go that far.
    Sent from my iPadŽ

  5. #5
    Registered User
    Join Date
    May 2006
    Posts
    903
    Actually, everyone sucks at pointers until they learn a little bit how memory works. When a variable is created, it is given a memory address for which has been allocated the necessary amount of memory. A pointer, is a variable for which no memory was allocated and you are given the control over where it should be 'located'. This pointer you just created could point to another variable in your program (they would kind of share the same home) or it could point to a character string which is stored in a constant memory address (i.e. "hello world" will be located in some memory address for your program to access and deleted at the end of its execution). Another thing you can do with pointers is allocate memory (using the 'new' operator, don't forget to 'delete' it after) to which you will have read or read/write access.

    Just like in the latter case, you don't always have write rights over a pointer. These rights are set using the 'const' keyword. Let's say you don't want the user to modify the character string to which you pointer is pointing (i.e. the first character of the string). Then it is expressed as follow:
    Code:
    const char* ptr = "Hello World";
    This is all good, trying to modify it will cause a compiler error unless you use some trick. Now what happens if you have allocated memory for a pointer to which many other pointers are pointing ? What the hell did that mean ? Who am I ? ARgghghh ! XD Let's say you have some resource that is shared by other pointers. Let's say it's a pointer to your whole game engine's framework and let's say we have a few pointers pointing to it. If your OS decides to -- for some obscure reason -- modify the location of your pointer, you're f***ed. Why is that ? Because your other pointers are still pointing to the old memory address. Here's that situation into code:
    Code:
    // This is a dumb use of memory allocation
    // but I couldn't think of anything else
    const GameEngine* myEngine = new GameEngine;
    const GameEngine* ptr = myEngine;
    
    // Here the OS perfoms its little trick, we're f***ed
    ptr->CallSomeUselessMethod(); // BANG ! Segmentation fault !
    There is a way to fix this though. You need to specify that you don't want the OS to perform its nifty little trick on you by adding another 'const' before the pointer '*' symbol (it's logical, it's a const pointer), like this:
    Code:
    const GameEngine const* myEngine = new GameEngine;
    const GameEngine* ptr = myEngine;
    
    // The OS can't perform its little trick here
    ptr->CallAnotherUselessMethod(); // You've saved yourself headaches
    This is something not very common though because you rarely have many pointers to a critical object, you usually pass the object directly. I just explain further how memory works and how pointers are so intimately related to it. Now I don't want you to go around and use const pointers everywhere but just keep in mind that it exists.

    [/end_of_my_teaching_trip] XD

    Edit: Just noticed I'm in the C forum. The article is still valid. Replace 'new' with malloc() and 'delete' with free() (I think).

  6. #6
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by Desolation
    A pointer, is a variable for which no memory was allocated and you are given the control over where it should be 'located'.
    Not true. The pointer does have memory allocated for it. The pointer itself takes up space. Thus, it has memory allocated for it.

    A better explanation would be:

    Pointers are just like any other variable. They hold a value. However, the value they hold is different than the value held by non-pointers. Pointers hold, as their value, an address of a variable of the type to which they point. Like so:
    Code:
    int *p;
    'p' holds as its value the address of an 'int', because that is the type to which it points. Since we didn't actually initialize 'p', it just has some random value, just like any other uninitialized variable.
    Quote Originally Posted by Desolation
    This pointer you just created could point to another variable in your program (they would kind of share the same home) or it could point to a character string which is stored in a constant memory address
    Not exactly. They can only hold the address of the type to which they point. Thus, our above integer pointer could not point to a string, because that would be a pointer to a character, not a pointer to an integer.
    Quote Originally Posted by Desolation
    (i.e. "hello world" will be located in some memory address for your program to access and deleted at the end of its execution). Another thing you can do with pointers is allocate memory (using the 'new' operator, don't forget to 'delete' it after) to which you will have read or read/write access.
    'new' and 'delete' are C++. This is the C forum. They'll need malloc, calloc, and free.
    Quote Originally Posted by Desolation
    Just like in the latter case, you don't always have write rights over a pointer. These rights are set using the 'const' keyword. Let's say you don't want the user to modify the character string to which you pointer is pointing (i.e. the first character of the string). Then it is expressed as follow:
    Code:
    const char* ptr = "Hello World";
    This is all good, trying to modify it will cause a compiler error unless you use some trick.
    "Hello World" is a string literal, and is not modifyable. Doing so is undefined behavior, and will likely crash your program.

    ...snip C++ example...

    A better example might be:
    Code:
    int x = 5;
    int *p, *q;
    
    p = &x; /* put the value of x's address in p */
    q = p; /* make q point to what p points to */
    
    *q = 7; /* change x to 7, using pointer q */
    All pointers do is store addresses. Think of giving your address out to all your friends. Now one of them comes over and burns your house down. Well, everyone has the same address, so when they show up, they'll all see the same end result, which is that someone burned your house down.


    Quzah.
    Hope is the first step on the road to disappointment.

  7. #7
    Registered User
    Join Date
    May 2006
    Posts
    903
    I had forgotten the first point about pointers taking up memory even before malloc() 'ing some. As for the types, I thought it was pretty obvious (except for polymorphism) that a pointer to a type could only point to a variable of the same type. Mmm.. I also edited about new and delete before you posted, sorry for that. Last thing, I know that the string litteral cannot modified (even if I haven't stated it) but what I wanted to point out is that trying to modify it would cause a compiler error over a segmentation fault since it is not allowed to modify a const variable.

    While we're at it, I might also add that if you free the memory you allocated for a pointer and then allocate new memory using malloc(), the address to which that pointer was before is not valid anymore. Using malloc() has returned another block of memory which we cannot assert anything about its location. This means that if we had pointers pointing to the old address, they have now all become invalid. They could be pointing to anything and it oftens causes a segmentation fault.

  8. #8
    Registered User
    Join Date
    Sep 2006
    Posts
    51
    wow..
    thx for the short tutorial on pointers!
    Some very useful info!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Compiling sample DarkGDK Program
    By Phyxashun in forum Game Programming
    Replies: 6
    Last Post: 01-27-2009, 03:07 AM
  2. weird seg fault
    By Vermelho in forum C Programming
    Replies: 3
    Last Post: 05-10-2008, 08:27 PM
  3. dllimport function not allowed
    By steve1_rm in forum C++ Programming
    Replies: 5
    Last Post: 03-11-2008, 03:33 AM
  4. Problem with Visual C++ Object-Oriented Programming Book.
    By GameGenie in forum C++ Programming
    Replies: 9
    Last Post: 08-29-2005, 11:21 PM
  5. c++ linking problem for x11
    By kron in forum Linux Programming
    Replies: 1
    Last Post: 11-19-2004, 10:18 AM