strncmp gives segmentation fault when comparing two strings

857 views Asked by At

I am trying to write a function which compares first two digits of a number, and since itoa is not available, I am using sprintf as found by googling previously to first convert number to string and then compare each digit. For some strange reason, I am getting seg faults when I run this. I tried same thing but using actual strings like strncmp("100", "101", 2) and it gives no issues. The problem is because of two sprintf statements which somehow messes up str2. I cannot find anywhere why this is happening and what I can do to fix it. Spent 2 hours on this before posting here. Would appreciate some help, if possible

int exists;
int id1 = 100;
int id2 = 101;
char str1[12];
char str2[12];
sprintf(str1, "%d", id1);
sprintf(str2, "%d", id2);
exists = strncmp(str1,str2,2);
printf("Res is %d\n", exists);

Edit: I've tried printf both str1 and str2 and they show 100 and 101 respectively. I also tried iterating thru char arrays but got seg fault again. I actually was able to run it successfully when I created a test file and it all ran so I am totally lost

Edit #2: To add context, this program has multiple files in it and some libraries are included in other files. Everything is properly surrounded by #ifndef. Question is can the order of file compilation produce this issue?

3

There are 3 answers

0
user3078855 On BEST ANSWER

Not 100% sure that I found the correct solution but I believe my issue was linked to malformed makefile. Specifically I previously had this:

CC = /usr/local/bin/gcc
CFLAGS = -Wall -g
... (omitting file list)
#build exe from .o files
$(PROJECT) : $(OBJS)
    $(CC) $(CFLAGS) $(OBJS) -o $(PROJECT)

And after I changed CC to CC = gcc, it started working. I had to strip my main.c before though and proceed slowly as noted above by simonc and Jonathan Leffler.

1
user3074230 On

."..and since itoa is not available,and since itoa is not available..." What the ... ?! Are you kidding us ? Include stdlib.h :)

#include <stdio.h>
#include <stdlib.h>

void main(void)
{
    int exists, id1 = 100, id2 = 101;
    char str1[12], str2[12];

    sprintf(str1, "%d", id1);
    sprintf(str2, "%d", id2);
    exists = strncmp(str1, str2, 2);

    printf("Res is %d\n", exists);
}

Any way ... when i check and test your posted code, all okay. Try to compile with other software (GCC, TurboC, and etc...).

btw, i didint find any logic in that mind when you comparing two string, which have been converted from integer to char, simply you can check that two integers...

1
microtherion On

Add

#include <string.h>

at the top. Procedure calls in modern C can misbehave in all sorts of ways if no prototype is in scope.