i have written a code in C. Which gets content from a while. and get command line argument from user, and concantenete that output with the content of file. These codes works properly on Ubuntu but getting Segmentation Fault on CentOS. Here are the codes :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXC 1024 /* if you need a constant, #define one (or more) */
char* trimew(char* str)
{
static char str1[99];
int count = 0, j, k;
// Iterate String until last
// leading space character
while (str[count] == ' ') {
count++;
}
// Putting string into another
// string variable after
// removing leading white spaces
for (j = count, k = 0;
str[j] != '\0'; j++, k++) {
str1[k] = str[j];
}
str1[k] = '\0';
return str1;
}
int main (int argc, char **argv) {
FILE *fptr;
char *c;
fptr = fopen("/usr/bin/.mypass", "r");
char command[MAXC] = "/usr/bin/foo LOAD=";
size_t len = strlen (command);
strcat (command, "\"");
strcat (command, trimew(fgets(c,20,fptr)));
strcat (command, "\"");
fclose(fptr);
int i;
for (i = 1; i < argc; i++) {
size_t arglen = strlen (argv[i]);
if (len + arglen + 2 > MAXC) {
fputs ("error: arguments exceed command storage.\n", stderr);
return 1;
}
strcat (command, " ");
strcat (command, argv[i]);
len += arglen + 1;
}
printf ("system (%s)\n", command);
// system (command);
}
I'm Running the Code on My Cloud Server where CentOS Linux release 7.9.2009 (Core) is Installed, there i'm getting Segmentation Fault error. But i tried to run on My Ubuntu PC and it works fine.
I tried to Debug it via gdb on CentOS. I got this :
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7a7cce9 in __GI__IO_getline_info () from /lib64/libc.so.6