Hi everybody I'm experiencing some problems with an array of strings that seem to be invading a reserved space of memory. The code is too large to post here, so I'll post the important part below:
int main ( ){
int i = 0, j = 0, k = 0, count = 0, numLinhas = 0, l = 0;
char string[100][100];
char line [17];
char str[4];
char str1[5];
char str2[4];
char str3[4];
FILE *p;
p = fopen("text.txt", "r");
while(fgets(line, sizeof line, p)!=NULL){
printf("%s", line);
strncpy(string[i], line, 17);
i++;
numLinhas++;
}
fclose(p);
char *temp[numLinhas];
After that it goes into a loop in which stores in string [i] the meaning of the statement contained in the file. The beginning of the for and three examples are shown below:
for (i = 0; i<numLinhas; i++){
sscanf( string[i], "%s %s %s %s" ,str1, str,str2, str3);
if(str[0]=='0' && str[1] == '0' && str[2]!= 'd') {
temp[i] = "NOP";
count++;
}
if(str[0]=='0'&& str[1] == '6' && str[2]!= 'd') {
sprintf(temp[i],"%s,%s" , "MVI B", str2);
count = count+2;
}
if(str[0]=='0'&& str[1] == '7' && str[2]!= 'd') {
temp[i] = "RLC";
count++;
}
The error is casual - it does not always happen. And it usually occurs when there is a call to sprintf. Ah yes! And below is the txt file I'm loading as an example:
0000 21a 11r 00r
0003 7Ea
0004 21a 12r 00r
0007 46a
0008 80a
0009 21a 13r 00r
000C 77a
000D 3Ea 01a
000F 3Da
0010 76a
0011 0Ad
0012 03d
0013 01d
Just saw something new. here's the compile window i'm getting:
marcos@john:~/Desktop$ ./paraler
0000 21a 11r 00rValor de l: 16
Valor de l: 1
0003 7Ea
Valor de l: 9
0004 21a 12r 00rValor de l: 16
Valor de l: 1
0007 46a
Valor de l: 9
0008 80a
Valor de l: 9
0009 21a 13r 00rValor de l: 16
Valor de l: 1
000C 77a
Valor de l: 9
000D 3Ea 01a
Valor de l: 13
000F 3Da
Valor de l: 9
0010 76a
Valor de l: 9
0011 0Ad
Valor de l: 9
0012 03d
Valor de l: 9
0013 01d
Valor de l: 9
string:0000 21a 11r 00r
string:
string:0003 7Ea
string:0004 21a 12r 00r
string:
string:0007 46a
string:0008 80a
string:0009 21a 13r 00r
string:
string:000C 77a
string:000D 3Ea 01a
string:000F 3Da
string:0010 76a
string:0011 0Ad
string:0012 03d
string:0013 01d
Segmentation fault
The strange thing is that I get some empty spaces of the string array... Does it have anything to do with the error?
strncpy(string[i], line, 17);
, if a line is 17 characters or more, a nul terminator is not written, and string[i] doesn't really contain a string. – nos Nov 30 '10 at 17:10