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
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);
}
You need to allocate space for script
char *script = malloc(/* string size */);
To be able to use it.
You didn't allocate any memory for script.
char *script; creates a pointer, but it has to point to something you've allocated, in your case its value is undefined. Use malloc to allocate the memory, and free when you're done.
change this line:
char *script;
to this:
char script[255];
The sprintf tries to write the result string to script, which you haven't initialised.
You're not allocating any memory for the variable script. The sprintf function expects that its first param is a pointer to already-allocated memory, but your script is never initialized, which means that it's null or garbage.
You are formatting into "script" without allocating any memory to receive the formatted string.
Instead, allocate:
char script[1024];
Related
I am working with a bunch of strings for logging. I want to refactor my code and make a new struct that combines the char, its length and allocated size. The idea is to make my internal string operations smoother and the code nicer to read, whilst assigning each string its own max allocated memory to keep the usage to a minimum but prevent stack overflow. I made this simple example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
char *str;
int size;
int max;
} Text;
void defText(Text *text, int max)
{
text->str=(char*) malloc(max * sizeof(char));
text->str="";
text->max=max;
}
int main() {
Text *a;
defText(a,50);
a->str="Test all you want";
printf("OUT: %s %zu %lu",a->str,strlen(a->str),sizeof(a->str));
return 0;
}
The function defText initializes and allocates memory. However, when I check the sizeof the char in my struct, I always get 8, no matter what I set in defText. Is this kind of struct handling strings and their properties together even possible? If so, what is wrong here?
There are several problems in your code, this is an example that cleans up these problems:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
char *str;
// you could use size to keep track of the strlen. That's particularly
// desirable if you find yourself calling strlen "a lot", since that
// function recalculates the length every time it's called
int size;
int max;
} Text;
void defText(Text *text, int max)
{
// no need to cast the return of malloc. In fact, sizeof(char) is defined by
// the standard to be 1 so you could take that out also.
text->str=malloc(max * sizeof(char));
// `=` is not the proper way to write strings in C, you must use strcpy
// or something similar. It looks like here you're simply trying to
// create an empty string.
//text->str="";
// per #JohnBollinger's comment, the best thing to do here to create
// an empty string is simply set to the first byte to the NUL
// terminator.
text->str[0] = '\0';
text->max=max;
}
int main() {
Text a; // store this in automatic memory, now the object exists without having to malloc
defText(&a,50); // Use & to pass the address of a to defText
// as mentioned, this is not the proper way to write data to a string in
// C. What you've done here is create a memory leak and point a.str to
// the string literal "Test all you want". Use strcpy (or similar) to
// write that string into the data you actually malloc'ed (using the dot
// operator now since `a` is no longer a pointer)
//a->str="Test all you want";
strcpy(a.str, "Test all you want");
// a.str is a pointer, and will always be 8 bytes on your system no matter
// the size of the memory it points to
printf("OUT: %s %zu %zu",a.str,strlen(a.str),sizeof(a.str));
// clean up allocated memory. Since we're about to exit, there's
// really no need to do this here (the OS will reclaim all allocated
// memory when the process ends), but if you're writing a more
// involved, long-running program, you need to be sure to handle
// memory allocations and deallocations appropriately as needed
free(a.str);
return 0;
}
Demo
The
a->str
is pointer .
the correct answer is
sizeof(*(a->str))
So i've make a program about an char array that is dinamically allocated, the program is not yet finished but i've got some different return values after i run the program, no warnings, no errors in compiler so i don't know why i get this also sometimes the program crashes..
#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>
#include <string.h>
int main(){
int n,i;
char *tab=NULL;
printf("New size of array: ");
scanf("%d",&n);
tab=(char*)malloc(n*sizeof(char));
memset(tab,'X',n*sizeof(tab));
for(i=0;i<n;i++)
printf("%c",tab[i]);
free(tab);
return 0;
}
In your memset you write n * sizeof(tab), I think you wanted to write :
n * sizeof(char)
You can also add a +1 add the end of your malloc and check the return value, just for security.
The C library function void *memset(void *str, int c, size_t n) copies the character c (an unsigned char) to the first n characters of the string pointed to, by the argument str.
memset(tab,'X',n*sizeof(char));
You've written n*sizeof(tab), you are copying the character X to unknown memory which might cause crash during runtime.
Look into this line:
memset(tab,'X',n*sizeof(tab));
You declared tab as a pointer, and a storage size of a pointer is more than one byte. Multiplying that by n which is the size of the array you want will cause you to copy data to memory space you're not allowed to access which is why you get a segmentation fault.
If you must use sizeof, then do this:
memset(tab,'X',n*sizeof(char));
or better yet, just do this:
memset(tab,'X',n);
because a char is one byte and n times 1 = n.
I am a beginner with c, and I am having a problem with scanf and strings.
here is an example I wrote of my problem.
#include <stdio.h>
#include <string.h>
int main(void)
{
char* string;
scanf("%s", &string);
if (strcmp(string, "Foo") == 0) //segmentation fault here
printf("Bar");
}
basically, this code compiles, but when I run it I get a segmentation fault in strcmp()
if I replace the "string" in that line with "&string" it works, but I get this error from the compiler
/usr/include/stdio.h:362:12: note: expected 'const char * __restrict__' but argument is of type 'char **'
which makes me think that this solution is not really ideal.
also If I declare string like this:
char string[100];
that works without any warnings, but that is also not ideal because I am not sure how large the string is going to be.
Is there a better solution I'm missing here, or are these my only options?
thank you.
char* string;
scanf("%s", &string);
string is not pointing to any valid memory location. Allocate memory using malloc to an array of characters and copy input to it. Make sure allocated memory has space for null termination character. Remember to free the memory to avoid leaks.
Just try that code
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
char* string;
string=(char *)malloc(3); /*allocate the memory to string cahr pointer(default pointer point to single byte and if you print pointer variable don't used & character)*/
scanf("%s", string);
if (strcmp(string, "Foo") == 0)
printf("Bar\n");
}
While declaring a char *. it will not having any memory location. so you have to allocate a
memory location before you use that variable.
char *p;
p=malloc(sieof(char) * size of string);
then you use scanf() function. it will work properly.
when we are accessing a unknown memory(ie unallocated memory). then it will through the segmentation fault
I am trying to copy a string into another char pointer variable using strcpy function.But I always get segmentation fault.Here is my code.
/* strcat example */
#include <stdio.h>
#include <string.h>
int main()
{
char str[100]="";
char *pch3;
strcpy(pch3,"Ravi");
//strcat(str,pch3); //Segmnetation fault.
puts(pch3);
return 0;
}
If I do the same thing in this one I still get segmentation fault.
else
{
misc_rec_cnt++;
fp1=fopen("breast-cancer-wisconsin-miscellaneous.data","a");
fprintf(fp1,"%s",line2);
fclose(fp1);
fp2=fopen("missingSCNs.data","a");
pch2=strtok(line2,",");
fprintf(fp2,"%s\n",pch2);
fclose(fp2);
//pch3=(char *)malloc(sizeof(char)*strlen(line3));
pch3 = strtok(line3,",");
while(pch3!=NULL)
{
if(strcmp(pch3,"?") == 0)
{
strcat(str1,"0");
strcat(str1,",");
}
else
{
//strcat(str1,pch3);
strcat(str1,",");
}
pch3 = strtok(NULL,",");
}
strlen1=strlen(str1);
memcpy(str2,str1,strlen1-1);
fp3=fopen("breast-cancer-wisconsin-miscellaneous-cleansed.data","a");
fprintf(fp3,"%s\n",str2);
fclose(fp3);
}
You need to allocate the space for pch3 before you copy to it. Use malloc to create a char array large enough to accomodate the elements of your source string before you copy it. What you are currently doing is declaring a char pointer and not initialising it. Therefore the memory location that it points to could be anywhere - and that means that you should probably not be attempting to write to it - which is why you are getting the segfault. Using malloc will allow you to allocate a region of memory that you are safe to write to and this will solve your problem (assuming the call to malloc succeeds). You cannot just go writing data to random memory locations without getting segfaults and access violations.
pch3 is a char pointer, but it doesn't have any storage associated with it which is the cause of the problem. Call malloc() to allocate some memory that the pch3 pointer can point to and you should be ok.
At this point you have a char pointer that is uninitialized and just pointing somewhere unknown. So try this:
pch3 = (char *)malloc(sizeof(char) * 100); /* 100 just as an example */
This tutorial might be helpful or this SO question: Allocating char array using malloc
pch3 is an unallocated pointer, so you're writing data to a location that doesn't exist. Did you mean to assign it to str?
char str[100]="";
char *pch3;
pch3 = str;
strcpy(pch3,"Ravi");
I'd recommend that you first allocate memory before copying data to a random place.
strcpy(pch3=(char*)malloc(sizeof("Ravi")),"Ravi");
but better check if it didn't return null pointer.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num = 1;
char* test[8];
sprintf(test[0],"%d",num);
printf("%s\n",test[0]);
}
char *test[8] is an array of 8 char *, or pointers to strings, and since you don't specify, they're all set to garbage values. So sprintf is trying to write data to who-knows-where.
You should use char test[8] instead, which allocates an array of 8 char, and then sprintf(test, "%d", num);.
UPDATE: If you want to use char * pointers, you should allocate space:
char *test = malloc(8 /* see note below */);
sprintf(test, "%d", num);
If you want to use an array of char * pointers, it works the same:
char *test[8]; // 8 pointers to strings
test[0] = malloc(8); // allocate memory for the first pointer
sprintf(test[0], "%d", num);
Keep in mind you would have to call malloc for each of test[0] through test[7] individually.
Also, as mentioned in the comments, if your compiler supports it you should use snprintf(). It's like sprintf but it takes an extra parameter which is the size of the buffer:
snprintf(test, 8, "%d", num);
and guarantees not to use more space than you allow it. It's safer, and if you need to, snprintf returns the amount of space it actually wanted, so if you gave it too little room you can realloc and try again.
Note: some will say this should be malloc(8 * sizeof(char)) (or sizeof *test). They are wrong (in my objectively-correct opinion; note the sarcasm)! sizeof(char) is guaranteed to be 1, so this multiplication is unnecessary.
Some advocate the usage of TYPE *p = malloc(x * sizeof *p) so that if TYPE changes, you'll only need to change it in one place, and sizeof *p will adapt. I am one of these people, but in my opinion you will rarely need to upgrade a char * to another type. Since so many functions use char * and would need to be changed in such an upgrade, I'm not worried about making malloc lines more flexible.
sprintf() does not allocate space for the string; you must do that yourself beforehand.
Look at your warnings:
test.c: In function ‘main’:
test.c:8: warning: ‘test[0]’ is used uninitialized in this function
You allocate an array of 8 pointers, but use one without initializing it. You must call malloc and store the result in test[0] before you can write to the memory pointed to by test[0]. You free it at the end.
A useful function, present in GNU and BSD, is asprintf, which will call malloc for you to allocate enough memory for the formatted string:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int num = 1;
char* test[8];
asprintf(&test[0],"%d",num);
printf("%s\n",test[0]);
free(test[0]);
return 0;
}
(Note that you pass the address of your pointer to asprintf — since your pointer is test[0], its address is &test[0].)
You did allocate space but you you are passing the wrong thing. Try this:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num = 1;
char test[8];
sprintf(test,"%d",num);
printf("%s\n",test);
}
int main()
{
char *str[5];
sprintf(str[0], "%d",55);
printf("%s\n",str[0]);
return 0;
}
This will be work. But, if you specify variable instead of integer constant value show the segmentation fault will be occur. This error will be happened at the time of sprintf function execution. Because user space memory access.