Advertising (This ad goes away for registered users. You can Login or Register)

Segfault in c code.

Programming on your favorite platform, for your favorite platform? Post here
Locked
Nickolas
Posts: 174
Joined: Sat Jan 22, 2011 3:14 pm
Location: In a black hole...

Segfault in c code.

Post 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).
Advertising
Image
Image
Image
Image
qwikrazor87
Guru
Posts: 2874
Joined: Sat Apr 21, 2012 1:23 pm
Location: The North Pole

Re: Segfault in c code.

Post by qwikrazor87 »

Try change "instruction" into a single pointer, not a double pointer.

Code: Select all

char *instruction = malloc(sizeof(char) * 3);
Advertising
PSP 2001 - TA-085 - 6.61 PRO-C2
PS Vita 3G - PCH-1101 - 3.65 HENkaku Ensō
Alcatel phone - Android 8.1.0
Laptop - Toshiba Satellite L305D-S5974 - Ubuntu 16.04 LTS
preloader
Posts: 81
Joined: Thu Feb 28, 2013 1:09 pm

Re: Segfault in c code.

Post 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.
Nickolas
Posts: 174
Joined: Sat Jan 22, 2011 3:14 pm
Location: In a black hole...

Re: Segfault in c code.

Post by Nickolas »

Works like a charm! Thank you guys :)
Image
Image
Image
Image
Nickolas
Posts: 174
Joined: Sat Jan 22, 2011 3:14 pm
Location: In a black hole...

Re: Segfault in c code.

Post 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?
Image
Image
Image
Image
Locked

Return to “Programming”