-1

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
  • 2
    `char *c;... fgets(c,20,fptr)` That causes Undefined Behaviour (of which seg fault is one possibility). Because `c` is an uninitialised pointer. It needs to point to a valid memory buffer. – kaylum Jun 16 '21 at 04:57
  • Also, should do error checking. For example, need to check return value of functions such as `fopen` and check `argc` before using `argv`. – kaylum Jun 16 '21 at 04:58
  • 1
    Always compile with warnings enabled, e.g. `-Wall -Wextra -pedantic` for gcc/clang or `/W3` for VS and you would have been told about the exact problem and the line on which it occurs, e.g. `"40:22: warning: ‘c’ is used uninitialized in this function [-Wuninitialized] strcat (command, trimew(fgets(c,20,fptr)));"` – David C. Rankin Jun 16 '21 at 07:30

1 Answers1

1
char *c;

is just a pointer.

fgets needs allocated storage to read the string to.

Try

char c[20];
Humpity
  • 152
  • 1
  • 9