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

Segfault in c code.

Post by Nickolas » Thu Sep 04, 2014 11:37 pm

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

User avatar
qwikrazor87
Guru
Posts: 2862
Joined: Sat Apr 21, 2012 1:23 pm
Location: The North Pole

Re: Segfault in c code.

Post by qwikrazor87 » Thu Sep 04, 2014 11:47 pm

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.60 PRO-C2
PS Vita 3G - PCH-1101 - 3.60 HENkaku Ensō
Maxwest Nitro 4 phone - Android 5.1
Laptop - Toshiba Satellite L305D-S5974 - Ubuntu 12.04 LTS

User avatar
preloader
Posts: 81
Joined: Thu Feb 28, 2013 1:09 pm

Re: Segfault in c code.

Post by preloader » Thu Sep 04, 2014 11:57 pm

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 » Fri Sep 05, 2014 7:19 am

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 » Fri Sep 05, 2014 12:05 pm

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

Post Reply

Return to “Programming”