SegFault caused by strtol

I'm using the following code segment:

<void decode_inst(char instruction[])
{
int i =0;

if(instruction[0] == 'r'){
current_instruction.type = "READ";
}else
current_instruction.type = "WRITE";

char* pch;
pch = strtok(instruction," "); //gets rid of the instruction and space
pch = strtok(NULL," "); //sets pch to the address part of instruction
int address = (int)strtol(pch,NULL,0);>

my intent is convert "r aeb2d86f0980" into an integer format. When I get to the strtol instruction I'm getting a segmentation fault. Any idea why?
How do you call your decode function? instruction should be either proper array, or dynamically allocated char pointer.
This is illegal:
1
2
char* instruction = "r aeb2d86f0980";
decode_inst(instruction);

Also your number is too large to fit into int varible.
man strtok wrote:
Be cautious when using these functions. If you do use them, note that:
* These functions modify their first argument.
* These functions cannot be used on constant strings.
* The identity of the delimiting byte is lost.
* The strtok() function uses a static buffer while parsing, so it's not thread safe. Use strtok_r() if this matters to you.
MiiNiPaa,

Here is the call to decode_inst:

ifstream inFile(L1.trace_file);
if(! inFile){
cout << "Error opening trace file, please check trace file name";
return 0;
}

while(inFile.getline(current_line,LINE_LENGTH)){
decode_inst(current_line);
...
}
If your file contains anything other than lines formatted as "xyz 123abc", even blank lines, then your function will fail.

Your first post appears to be C, but your last post shows that you are using C++. Why are you trying to use C stuff when you have C++ available to you? (It is misunderstanding the C stuff that is causing you to fail.)

1
2
3
4
5
6
7
8
9
10
11
12
int main()
{
  ...

  ifstream inFile( ... );
  ...

  string current_line;
  while (getline( inFile, current_line ))
  {
    decode_inst( trim_inplace( current_line ) );  // http://www.cplusplus.com/faq/sequences/strings/trim/
  }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void decode_inst( string s )
{
  if (s.empty()) return;

  istringstream ss( s );
  string            name;
  unsigned long int value;

  ss >> name >> hex >> value;

  if (!ss.eof())
  {
    cout << "Congratulations. The instruction name was " << name << " and the value was " << hex << value << ".\n";
  }
  else
  {
    cout << "Alas, the not-empty line was not of the form \"NAME  HEX_VALUE\".\n";
  }
}

Hope this helps.

[edit] Edited to fix input of hex value.
Last edited on
Topic archived. No new replies allowed.