Thread: Segfault using logical OR on for loop.

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Mar 2013
    Location
    Chiang Mai, Thailand.
    Posts
    9

    Segfault using logical OR on for loop.

    I've received a segmentation fault in this part of code:
    Code:
    for (; str[i] != '\0' || str[i] != ' '; i++)
    {
            result[result_pos] = str[i];
            result_pos++;
    }
    which, should mean:
    Code:
    If str[i] is not equal to NULL character nor ' '; then, keep printing the chars within the word to variable result.
    To understand what the function does, here's the whole code:
    Code:
    static char result[999];
    
    /* char *split_word(const char *str, long n);
     * Splits a string word-by-word. Where N is the word number. */
    char *split_word(const char *str, long n)
    {
        size_t result_pos = 0;
        long scr;
        size_t i = 0;
    
        for (scr = 0; scr < n; scr++)
        {
            for (; str[i] != ' '; i++) ; /* Scrolls forward to the desired word */
            i++; /* Skip one char (the space). */
        }
    
        for (; str[i] != '\0' || str[i] != ' '; i++)
        {
            result[result_pos] = str[i];
            result_pos++;
        }
    
        return result;
    }
    I'm trying to accomplish an easier way round to split string by word than using "strtok_r()". It might sound like "re-inventing the wheel", but... i will try to make it neat later.

    The code looks okay, why would it segfault? how can i fix that?
    Last edited by milo64; 03-10-2013 at 12:03 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. logical not !7 logical whaaaa?
    By Charbot in forum C Programming
    Replies: 2
    Last Post: 03-22-2011, 07:19 PM
  2. Logical! Logical! Why do you have to be so Logical?
    By g8ortech14 in forum C Programming
    Replies: 24
    Last Post: 09-20-2010, 02:40 PM
  3. getenv() causes segfault in recv() loop
    By MK27 in forum Networking/Device Communication
    Replies: 3
    Last Post: 12-05-2008, 02:04 PM
  4. logical AND...OR
    By Chaplin27 in forum C++ Programming
    Replies: 2
    Last Post: 02-14-2005, 11:50 AM
  5. Logical And
    By shiju in forum C Programming
    Replies: 6
    Last Post: 01-11-2004, 11:15 AM

Tags for this Thread