PDA

View Full Version : Segmentation fault: Cannot access memory at address



Joelito
05-15-2014, 06:17 PM
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++;
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?

Matticus
05-15-2014, 06:31 PM
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.

anduril462
05-15-2014, 07:00 PM
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.