Thread: Segmentation fault: Cannot access memory at address

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

    Unhappy Segmentation fault: Cannot access memory at address

    This is my 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 = '\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);
    	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
    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
    Long Beach, CA
    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
Website Security Test