im trying a simple program that will read a string, a capital letter, and 2 floats from input.
no matter how much i debug, change, or check the code or input, i keep getting segmentation fault at the last token read.
the input i enter is: text A,1,2
. i would like the program to ignore all white spaces and commas between the capital letter and values.
#include <stdio.h>
#include <string.h>
int main(){
char *value, *string;
char buffer[100];
float x;
if(fgets(buffer, sizeof(buffer), stdin)==NULL)
printf("empty input\n");
string = strtok(buffer, " ");
if(strcmp(string, "text")==0){
if((value = strtok(NULL, " \t\n")!=NULL)) /*seg.falt causes here*/
sscanf(value, " %f", &x); /*or here*/
}
}
if i print the value of value
in the console with p value
it says 0x1 <error: cannot access memory at adress 0x1
and i assume its a null pointer, but why though? the token should have 2
in it.
any insights on what am i missing?
Compiling your program with a recent GCC produces this warning:
t.c: In function ‘main’:
t.c:15:23: warning: assignment to ‘char *’ from ‘int’ makes pointer from integer without a cast [-Wint-conversion]
15 | if((value = strtok(NULL, " \t\n")!=NULL)) /*seg.falt causes here*/
| ^
There is a high chance that fixing the parenthesis to do what you wanted them to do will fix the crash:
if ((value = strtok(NULL, " \t\n")) != NULL)
P.S. You should get into a habit of building your programs with gcc -Wall -Wextra
.