Find the answer to your Linux question:
Results 1 to 2 of 2
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1

    execl and sprintf not working together


    I wrote a C wrapper to execute a shell program. I used execl to call the shell script and it pass some arguments as well. Passing command line arguments (using argv[]) works fine. But, I wanted to pass an integer as well.

    I will paste a sample code here. It works pretty fine in a machine with "gcc version 3.2.2 20030222 (Red Hat Linux 3.2.2-5)". But, it give segmentation fault in a machine with "gcc version 4.1.2 20070626 (Red Hat 4.1.2-13)".

    Here is a sample code:
    #include <unistd.h>

    main (int argc, char *argv[]) {

    int ret, userid, fd;
    char *user_id;
    sprintf( user_id, "%d", userid );
    ret = execl ("", "", user_id ,argv[1],argv[2], argv[3], argv[4], (char*)0);
    if (ret==-1) {
    printf("Error occured during exec, exiting\n");
    exit (1);
    #! /bin/bash

    echo "first $1"
    echo "second $2"
    echo "third $3"
    echo "fourth $4"

    Here, sprintf function looks fine and it gets printed in the next line. But, execl is not working. I tried passing user_id like "(char *)user_id, but didn't work.

    The funny thing I noticed here is, this code won't work even if you remove 'user_id' from execl statement. But, it will work if you remove sprintf() as well. As I mentioned above the same code works pretty fine in a machine with "gcc version 3.2.2 20030222 (Red Hat Linux 3.2.2-5)"

    Any ideas???.


  2. #2

    Wink yes, got it

    it got fixed. The problem was with memory allocation. I defined 'user_id' like:

    char *user_id=(char *)malloc(11);

    Now, the script is working fine.


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts