Page 1 of 1

Segfault in c code.

Posted: Thu Sep 04, 2014 11:37 pm
by Nickolas
Its probably some glaring mistake I can't seem to spot. I have a file that looks something like:

Code: Select all

abc 10
bgf 20
gfg 68
and so on.
And I am trying to parse it in C, ending up in segmentation fault (11).
Here's the code:

Code: Select all

char** instruction = malloc(sizeof(char) * 3);
	int instructionValue = 0;

    while(fscanf(inputFile, "%s %d",instruction,&instructionValue) != EOF)
    {
    	if(strncmp(instruction,"hlt",3) == 0)
    	{
    		printf("YEAH!\n");
    	}
    }

    fclose(inputFile);
P.S. Debugged with LLDB, EXC_BAD_ACCESS (line 26, the head of the while loop).

Re: Segfault in c code.

Posted: Thu Sep 04, 2014 11:47 pm
by qwikrazor87
Try change "instruction" into a single pointer, not a double pointer.

Code: Select all

char *instruction = malloc(sizeof(char) * 3);

Re: Segfault in c code.

Posted: Thu Sep 04, 2014 11:57 pm
by preloader
qwikrazor87 wrote:Try change "instruction" into a single pointer, not a double pointer.

Code: Select all

char *instruction = malloc(sizeof(char) * 3);
yes, it should work fine.

Re: Segfault in c code.

Posted: Fri Sep 05, 2014 7:19 am
by Nickolas
Works like a charm! Thank you guys :)

Re: Segfault in c code.

Posted: Fri Sep 05, 2014 12:05 pm
by Nickolas
Update: Segfault is now gone, "hlt" is recognised (I changed %s to %3s) but the instructionValue it is supposed to read turns out to be 1 while in the file it is 0. Any ideas?