If-statement segfault, not sure how to fix.
I've been trying to run some code, but I keep running into issues with if-statements of all things. The code basically looks like this:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 40
typedef struct stuff{
int *digit;
}stuff;
int main()
{
func("0123456789abcdef0123456789abcdef01234567");
}
stuff *func(char *str)
{
stuff *buff = malloc(40 * sizeof(stuff));
if(str == NULL || buff == NULL)
return NULL;
else
{
if(strlen(str) == 40) // Crashes here
{
// Execute code 1
puts("The string has exactly 40 chars");
return buff;
}
else if(strlen(str) < 40) // Crashes here too
{
// Execute code 2
puts("The string has less than 40 chars");
return buff;
}
else // And also here
{
// Execute code 3
puts("The string has more than 40 chars");
return buff;
}
}
}
I've tested each code (1, 2, and 3) individually, so I know they work. I've also tried replacing the strlen(str) in every if-statement with normal integers, and the code worked also.
When I prompted the program to print put strlen(str) I received integer values, so that;s fine too.
When I tried to debug my program, it stated that the program does indeed break when I enter an if-statement, but I'm not sure why. Any ideas?
EDIT: Some one requested my full code to better understand my issue, but since this is a homework assignment I don't want to be accused of cheating, or laziness. Instead, here's a similar (but more complete) code where the exact same crash/segfault, in the exact same place occurs.
Posted Jul 21, 2017, 10:16 PM UTC · edited