In the code below the debugger shows no error but when i run this piece of code inside a function scope char* s
is also in the function scope the debugger gives a segmentation error for the strlen function. Would adding char* s
as a parameter solve the problem? Or is it something else?
#include <locale.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <dirent.h>
#include <locale.h>
#define SIZE1 100
#define SIZE2 2000
int main(){
const char *getFileExtension(const char *filename);
char tags[100][2000];
char files[100][2000];
char paths[100][2000];
char textfiles[100][2000];
char orph[100][2000];
int i,j,k=0;
char *s;
for(i=0;i<SIZE1;i )
{
if(strncmp(getFileExtension(files[i]),"txt",3)==0)
{
strcpy(textfiles[k],files[i]);
k ;
}
}
k=0;
for(i=0;i<SIZE1;i )
{
for(j=0;j<SIZE1;j )
{
if(strcmp(tags[i],textfiles[j])!=0)
{
snprintf(s,strlen(tags[i]),"%s",tags[i]);
s[strlen(s)-1]= '\0';
strcpy(orph[k],s);
k ;
}
}
}
return 0;
}
const char *getFileExtension(const char *filename)
{
const char *dot = strrchr(filename, '.');
if(!dot || dot == filename)
return "";
return dot 1;
}
CodePudding user response:
You declared uninitialized arrays
char tags[100][2000];
char files[100][2000];
char paths[100][2000];
char textfiles[100][2000];
char orph[100][2000];
So using them in standard C string functions like for example
if(strcmp(tags[i],textfiles[j])!=0)
{
snprintf(s,strlen(tags[i]),"%s",tags[i]);
invokes undefined behavior.
It seems the function getFileExtension
also does not set elements of the array files
in this call.
getFileExtension(files[i])
Also the pointer s
char *s;
used in this statement
snprintf(s,strlen(tags[i]),"%s",tags[i]);
also has an indeterminate value.
CodePudding user response:
your tags array is not initialized. so strlen has undefined behavior. snprintf requires the size of available space not the length of the (uninitialized) contents. you should use sizeof instead of strlen in the snprintf call.