Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segmentation fault sprintf [c]

Tags:

c

shell

I need to pass two args to a shell script, here is the code:

#include <stdio.h>

#include <stdlib.h>

void main()
{
char *script;
int lines = 1;
sprintf(script, "/...path.../line.sh %d %d", lines, lines);
system(script);
}

The script works well, ive tried. But I always get Segmentation fault. The question is: why?

Thanks

like image 746
shaggy Avatar asked Dec 21 '22 11:12

shaggy


2 Answers

You are writing to the memory location pointed to by script which hasn't been allocated any memory.

Try something like:

#include <stdio.h>

#include <stdlib.h>

void main()
{
    char script[100]; // Allocate as much as you need here for your string, not
    int lines = 1;    // necessarily 100
    sprintf(script, "/...path.../line.sh %d %d", lines, lines);
    system(script);
}
like image 113
Paul Avatar answered Dec 24 '22 01:12

Paul


You need to allocate space for script

char *script = malloc(/* string size */);

To be able to use it.

like image 20
sidyll Avatar answered Dec 24 '22 02:12

sidyll