Segmentation fault: Cannot access memory at address

This is a discussion on Segmentation fault: Cannot access memory at address within the Linux Programming forums, part of the Platform Specific Boards category; This is my code: Code: #include <stdio.h> #include <limits.h> #include <stdlib.h> int parse_string (const char *s1, char *s2) { int ...

  1. #1
    Registered User Joelito's Avatar
    Join Date
    Mar 2005
    Location
    Tijuana, BC, México
    Posts
    308

    Unhappy Segmentation fault: Cannot access memory at address

    This is my code:
    Code:
    #include <stdio.h>
    #include <limits.h>
    #include <stdlib.h>
    
    int parse_string (const char *s1, char *s2) {
    	int pos = 0;
    	while ( (*s1 != '\0') || (*s1 != '\t') ) {
    		*s2 = *s1;
    		s2++;
    		s1++;
    		pos++;
    	}
    	*s2 = '\0';
    	return pos;
    }
    
    int main() {
    	FILE *ptr;
    	int index;
    	printf ("We're going to read the first five entries in pkg-config:\n");
    	ptr = popen ("pkg-config --list-all", "r");
    	char line[LINE_MAX];
    	index = 0;
    	while ( (index <= 5) && (fgets(line, LINE_MAX, ptr) != NULL) ) {
    		char *tmp = malloc (LINE_MAX);
    		parse_string (line, tmp);
    		printf ("%s", tmp);
    		free (tmp);
    		index++;
    	}
    	fclose (ptr);
    	return 0;
    }
    I'm trying to read the first entries and remove the tab character, but it gives me Segmentation fault, any ideas?
    * PC: Intel Core 2 DUO E6550 @ 2.33 GHz with 2 GB RAM: Archlinux-i686 with xfce4.
    * Laptop: Intel Core 2 DUO T6600 @ 2.20 GHz with 4 GB RAM: Archlinux-x86-64 with xfce4.

  2. #2
    Registered User
    Join Date
    Jun 2011
    Posts
    2,382
    Code:
    while ( (*s1 != '\0') || (*s1 != '\t') )
    You have the wrong logic here. When will this ever be false? (Hint: it won't.)

    You should also check the return value of "malloc()" to make sure it successfully allocated memory before trying to use that memory.

  3. #3
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,499
    Also, don't forget to check that popen() succeeded before you use ptr. If ptr is NULL, print a useful error message (e.g. via perror) and exit.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Access Violation: Segmentation Fault help
    By Isaiah in forum C Programming
    Replies: 4
    Last Post: 02-09-2012, 06:53 AM
  2. Replies: 4
    Last Post: 10-27-2011, 05:17 AM
  3. How to access a Particular bit of an Memory address ????
    By Gaurav Singh in forum C Programming
    Replies: 2
    Last Post: 10-16-2011, 02:11 PM
  4. Getting Access Violation (Segmentation Fault)
    By Brownie in forum C++ Programming
    Replies: 2
    Last Post: 09-26-2008, 11:43 AM
  5. access violation (segmentation fault)
    By MarlonDean in forum C++ Programming
    Replies: 7
    Last Post: 05-16-2008, 05:02 AM

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