Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

seg faulting on array declaration

Status
Not open for further replies.

rpeters1

Programmer
Oct 3, 2005
2
US
i havent programmed in C in years, i need to however for a project.

anyway, i'm reading in a data file and parsing it using basic file pointers. i read in all the data fine. however, when i try to declare a simple array, say, int my_array[10];, it seg faults. if i remove the code that reads in the data and declare the same array, it works fine.

any ideas? i can post the code if needed. thanks!
 
If the seg fault is showing on the array declaration, it could be very misleading. Your error could be somewhere before the declaration. Here are a few things I would try:

1. comment out the int my_array[10]; line and see if you still get seg fault. If you do, do #2, if not then post the code.

2. put a printf statement before array declaration. If the seg fault happens before the printf is executed, go up a few lines and try again. Until you find the exact line where the seg fault is happening.

If 1 & 2 fail, post the code.
 
here is the code. it actually now seems that i can have an array of size 1 and it wont seg fault. a value of 4 will seg fault at the end of the program (after data is printed). a value of 5 will not seg fault. a value of 20 will seg fault before the data is printed.

should i use malloc?



#include <stdio.h>



int main(int argc, char *argv[])
{
int my_array[1];
FILE *ifp;
char *data;
int num_places = 0, num_transitions = 0, init_marking;

ifp = fopen ("input.dat", "r");

if (ifp == NULL)
{
fprintf(stderr, "Can't open input file!\n");
return 0;
}
else
{

fscanf(ifp, " PN PLACES: ");
while (fscanf(ifp, "%s", data) != EOF && (strcmp(data, "PN") != 0))
{
printf("%s", data);
num_places++;
}

printf("\n");

fscanf(ifp, " TRANSITIONS:");
while (fscanf(ifp, "%s", data) != EOF && (strcmp(data, "PN") != 0))
{
printf("%s", data);
num_transitions++;
}

printf("\n");

int i;
for (i = 1; i <= num_transitions; i++)
{
fscanf(ifp, " PLACES FOR INPUT %s:", data);
while (fscanf(ifp, "%s", data) != EOF && (strcmp(data, "PN") != 0))
printf("%s", data);

printf("\n");
}

for (i = 1; i <= num_transitions; i++)
{
fscanf(ifp, " PLACES FOR OUTPUT %s:", data);
while (fscanf(ifp, "%s", data) != EOF && (strcmp(data, "PN") != 0))
printf("%s", data);

printf("\n");
}

fscanf(ifp, " INITIAL MARKING: %s", data);
printf("%s", data);

printf("\n");

fscanf(ifp, " PN MAX TRANSITIONS FIRING: %s", data);
printf("%s", data);
}

return 0;
}
 
Dangling pointer.
Code:
 char *data;
Point to writeable memory to avoid seg faulting. Or use an array.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top