Segmentation Fault using SQLite3 with C - c

I'm trying to make a C program work and I'm getting mad. This is my code simplified to find the error:
#include <stdio.h>
#include <unistd.h>
#include <sqlite3.h>
int main(){
sqlite3 *conn;
sqlite3_stmt *res;
const char *tail, *sqlresult;
sqlite3_open("cubecat", &conn);
char buffer,query;
int id;
id= 1;
buffer = 'a';
if(buffer == 'a') snprintf(&query,100,"SELECT start FROM payloads WHERE id=%d", id);
printf("%s",&query);
int error = sqlite3_prepare_v2(conn, &query, 100, &res, &tail);
printf("%d",error);
}
The error is exactly on "sqlite_prepare_v2" function, because if I comment that line, there's no Segmentation Fault.
Thank you in advance!

char query;
snprintf(&query,100,"SELECT start FROM payloads WHERE id=%d", id);
This is what's wrong. query only reserves memory for one character. There's a reason the 2nd argument of snprintf() specifies the size. This code should be modified like this:
char query[100];
snprintf(query, sizeof(query), "SELECT start FROM payloads WHERE id=%d", id);

Related

Including stdlib.h causes code to be unable to be compiled properly

I have a piece of code when I need to include stdlib.h. When I do not include this header, I have no problems compiling my code, but the moment I include the header, my code refuses to compile. It tells me that it expected an identifier or "(" before numerical constant. I have looked through my code and cannot find any issue, and as stated, the code compiles perfectly without including that header.
I am new to C, so excuse my poor code, I am simply wanting to figure out why it would be giving me this error.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int execute(char **args)
{
}
char** parse(void)
{
char command[256];
fgets(command, sizeof(command), stdin);
char delimiter[] = " ";
char * pointer = strtok(command, delimiter);
int tokens = 0;
char ** final_command;
while (pointer != NULL)
{
// final_command = (char**)realloc(final_command,
// (tokens+1)*sizeof(char*));
//printf("%s\n", pointer);
//pointer = strtok(NULL, delimiter);
}
}
int main(int argc, char **argv)
{
int EXIT_SUCCESS = 1;
do
{
printf("MyShell> ");
char ** command = parse();
} while (EXIT_SUCCESS);
return EXIT_SUCCESS;
}
I compile using the command gcc -o MyShell MyShell.c
The exact error I am getting says "error: expected identifier or '(' before numeric constant int EXIT_SUCCESS = 1;"
EXIT_SUCCESS is a standard macro (definition) in C. Do not use it as a variable name.
Like NULL, EXIT_SUCCESS is a macro defined in <stdlib.h>, if you include <stdlib.h> you must not use this identifier for other purposes.
In any case your code does not make much sense because it looks like you've got an infinite loop there in main.

Segmentation Fault (core dump) with Files (C- linux)

I'm getting a segmentation error (core dump) when I try to run this. It compiles perfectly but I get the error, and I don't know why. There must be a problem with a file writing because without this works good. Any help would be great. Thanks!
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <crypt.h>
#include <string.h>
int
main(void)
{
FILE *f=fopen("shadow1.txt","w");
if (f=NULL)
{
printf("ERROR");
}
unsigned long seed[2];
char salt[] = "$1$........";
const char *const seedchars =
"./0123456789ABCDEFGHIJKLMNOPQRST"
"UVWXYZabcdefghijklmnopqrstuvwxyz";
char *password;
int i;
/* Generate a (not very) random seed.
You should do it better than this... */
seed[0] = time(NULL);
seed[1] = getpid() ^ (seed[0] >> 14 & 0x30000);
/* Turn it into printable characters from ‘seedchars’. */
for (i = 0; i < 8; i++)
salt[3+i] = seedchars[(seed[i/5] >> (i%5)*6) & 0x3f];
/* Read in the user’s password and encrypt it. */
password = crypt(getpass("Password:"), salt);
/* Print the results. */
//fprintf(f,"%s $ %s",password);
printf("Success Registration to file !");
fclose(f);
return 0;
}
if (f=NULL)
{
printf("ERROR");
}
was the problem...
void Register(char u,char p) {
you probably want these to be char * because of the fprintf that treats them as strings:
fprintf(f,"%s $ %s",u,p);
and since you pass char *s in:
char *password,*username;
//...
Register(username,password);
This would most likely have been caught by compiler warnings. It is a lot faster to get your answer from the compiler than from here.
If you can't figure out why your program isn't working, you can enable all the warnings you should need with -Wall -Wextra and turn warnings into errors with -Werror.
You are not allocating space to hold username so it will segfault on the scanf.

Concatenate an environment variable and a string in C and feed to fopen()

I have very little knowledge about C and I can't get this simple task to work:
#include <stdio.h>
#include <string.h>
void load_hex_fw() {
char *warea = getenv("WORKAREA");
char hex[] = "/path/to/fw.hex";
char hexfile; // several trials done here (*hexfile, hexfile[500], etc.)
strcat(hexfile, *warea);
strcat(hexfile, hex);
printf("## %s\n", hexfile);
FILE *file = fopen(hexfile, "r");
fclose(file);
}
The above code basically opens a file for reading. But since the absolute path of the hex file is very long (and I'm also thinking of reusing this function in the future), I need to feed fopen() with a flexible hexfile variable. Googling string concatenation always gives me strcat(), or strncat, but I'm always getting a segmentation fault. I'm getting confused with pointers and references. Any help is greatly appreciated. Thanks in advance!
I have added some corrections and comments in your code, this should help you:
void load_hex_fw() {
char *warea = getenv("WORKAREA"); //check if getenv returns null
if(warea == NULL)
{
return;
}
char hex[] = "/path/to/fw.hex";
char *hexfile = NULL;//you need char buffer to store string
hexfile = malloc(strlen(warea) + stren(hex) + 1);//ENsure hexfile holds full filename
strcpy(hexfile,warea); //assuming you hold path in warea
strcat(hexfile, hex);//Assuming ypu hold filename in hex
printf("## %s\n", hexfile);
FILE *file = fopen(hexfile, "r");// check if fopen returns NULL
fclose(file);
free(hexfile);
}
asprintf allocates memory for you
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
void main() {
char *warea = getenv("WORKAREA");
if (!warea) {
warea = "default"; // or exit
}
char hex[] = "/path/to/fw.hex";
char *hexfile;
asprintf(&hexfile, "%s%s", warea, hex);
printf("## %s\n", hexfile);
// ...
free(hexfile);
}
it accepts 0 but result is hardly what you want for fopen
## (null)/path/to/fw.hex

segmentation fault on regex function

If I had this code all inside just one function, I could get everything working fine, but now my problem is that I can't read the results of my regex. When I try printing the first result, I get a segmentation fault. Instead, I was expecting the first regex result to appear of "T/2/b".
Also, the word "Matches" appears on the screen right before the segmentation fault occurred.
Is there something I'm missing?
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <regex.h>
typedef struct{
char str[1000];
} regex;
long regexmatch(const char* str,const char* regexs,size_t nummatch,regex** reg){
regex_t r;regmatch_t match[nummatch];
if (regcomp(&r,regexs,REG_EXTENDED) != 0){return -1;}
if (regexec(&r,str,nummatch,match,0)!=0){regfree(&r);return -1;}
size_t i=0;
for (i=0;i<nummatch;i++){
if (match[i].rm_so > -1){
memset((**reg).str,0,1000);
memcpy((**reg).str,(char*)(str+match[i].rm_so),match[i].rm_eo-match[i].rm_so);
(*reg)++; //this is where I load the result into the struct and advance the pointer.
}
}
char *p=(**reg).str;
*p='\0';
regfree(&r);
return 0;
}
int main(){
char buf[1000];
memset(buf,0,1000);
regex* r=(regex*)buf;
if (regexmatch("T/2/b","([A-Z]+)/([0-9]+)/([a-z]+)",10,&r)==0){
printf("Matches\n");
printf("%s\n",r->str); //causes segmentation fault. Expecting a "T/2/b" to be displayed instead.
}
}

Problems with strtok in c linux

I have the following code:
#include <stdio.h>
#include <stdlib.h>
FILE * f_enter;
void CleanLineFeed(char * pCad)
{
char *cTmp;
char *ptr;
cTmp=pCad;
ptr = strtok(cTmp, "\r\n\r");
strcpy(pCad, ptr);
}
int main(int argc, char *argv[])
{
char datenter[127];
int i;
f_enter=fopen("data.txt","r");
if(f_enter == NULL)
{
printf("No data.txt.\n");
return 1;
}
while ( fgets(datenter, 127, f_enter) )
{
CleanLineFeed(datenter);
for(i=0; i < strlen(datenter);i++)
{
printf("%c-%0X\n",datenter[i], datenter[i]);
}
printf("----------------------\n");
}
return 0;
}
when i run it on Windows there is no error but
when i run it on Linux give me a segmentation fault error
Please, i strongly appreciate some kind of help
you forgot to
#include <string.h>
Man page on Ubuntu 14.04 for strcpy says "The strings may not overlap".
"CleanLineFeed" performs an overlapped strcpy().
( This Link describes the issue )
Windows implementation of "strcpy" may differ from Linux's implementation,
which may explain why one crashes and the other doesn't.

Resources