Sprintf [c] segmentation error

I need to pass two arguments 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 it. But I always get a segmentation error. Question: why?

thanks

+4
source share
7 answers

You write to a memory location pointed to by a script that has not 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); } 
+5
source

You need to make room for the script

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

To use it.

+3
source

You have not allocated memory for the script .

char *script; creates a pointer, but it should point to what you highlighted, in your case its value is undefined. Use malloc to allocate memory and free when you are done.

+2
source

change this line:

 char *script; 

:

 char script[255]; 
+1
source

sprintf trying to write the result string to a script that you did not initialize.

0
source

You do not allocate any memory for the script variable. The sprintf function expects that its first parameter is a pointer to memory already allocated, but your script never initialized, which means that it is null or garbage.

0
source

You format in a "script" without allocating memory to get a formatted string.

Instead, highlight:

char script[1024];

0
source

All Articles