Thread: Segmentaion Fault in For Loop dereferencing a pointer

  1. #1
    Registered User
    Join Date
    Jan 2016
    Posts
    45

    Segmentaion Fault in For Loop dereferencing a pointer

    Hi,
    I get a segmentation fault whenever I try to dereference a pointer in a for loop. What is the reason and is there a solution to this problem?

    Here is some sample code that exhibits the problem:
    Code:
    #include <stdio.h>
    #define LENGTH 5
    
    
    int main()
    {
        int* pointer = 0;
        for (int i = 0; i < LENGTH; i++)
        {
            *pointer = (*pointer) + 1;
            printf("%d", *pointer);
        }
        printf("\n");
    }
    note for above code, I could have *pointer = 0; in the for loop and I'd still get the same error.

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    Where are you allocating memory for that pointer?

    Jim

  3. #3
    Registered User
    Join Date
    Jan 2016
    Posts
    45
    Hello,
    I understand now, thank you.

    My solution:
    Code:
    #include <stdio.h>
    #define LENGTH 5
    
    
    int main()
    {
    	int num = 0;
    	int* pointer = &num;
    	for (int i = 0; i < LENGTH; i++)
    	{
    		*pointer = (*pointer) + 1;
    		printf("%d", *pointer);
    	}
    	printf("\n");
    }

  4. #4
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    While you have now initialized the pointer, I doubt that the output is what you really want. Perhaps you should be dynamically creating an array of int of size LENGTH?

    Jim

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. passing a pointer to string giving segmentaion fault
    By Alexpo in forum C Programming
    Replies: 15
    Last Post: 10-10-2008, 05:11 AM
  2. Replies: 4
    Last Post: 08-27-2007, 11:51 PM
  3. segmentaion fault with File Input/Output
    By sara.stanley in forum C Programming
    Replies: 7
    Last Post: 04-04-2006, 03:57 AM
  4. dereferencing a void pointer
    By cricket in forum C Programming
    Replies: 8
    Last Post: 09-12-2003, 04:09 PM
  5. Dereferencing Pointer
    By Unregistered in forum C Programming
    Replies: 2
    Last Post: 02-01-2002, 07:52 AM

Tags for this Thread