I want to xor a certain value on all of my chars in a char array. I have some code that works all fine except for the xor line:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void obfuscate(FILE *file, char *input, char *variableName)
{
int i;
int size = (int)strlen(input);
char a = 65;
fprintf(file, "%s: %s -> ", variableName, input);
for(i = 0; i < size; i++)
{
input[i] = (char)(input[i] ^ a);//I am causing a segmentation fault
fprintf(file, "0x%x, ", input[i]);
}
return;
}
int main()
{
char *a = "MyString";
FILE *file = fopen("out.txt", "w");
obfuscate(file, a, "a");
fclose(file);
}
I use the normal gcc compiler with gcc in.c -o out.o on a linux machine.
If I comment the line with the xor operation it works just fine. Any help is highly appreciated, my own research did not result in a solution.
Try below solution with dynamic memory.
In char *a = "MyString"; char *in = malloc(sizeof(a));
a is pointing to code section we can't alter it. &
in is pointing to heap section, so we can modify it any no.of times.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void obfuscate(FILE *file, char *input, char *variableName)
{
int i;
int size = (int)strlen(input);
char a = 65;
fprintf(file, "%s: %s -> ", variableName, input);
for(i = 0; i < size; i++)
{
input[i] = (char)(input[i] ^ a);//I am causing a segmentation fault
fprintf(file, "0x%x, ", input[i]);
}
return;
}
int main()
{
char *a = "MyString";
char *in = malloc(sizeof(a));
strcpy(in, a);
FILE *file = fopen("out.txt", "w");
obfuscate(file, in, "a");
fclose(file);
free(in);
}
Related
So I am just trying to learn C and have decided to program a simple calendar where you can add events etc. It is working almost perfectly however, when it tries to read from the file containing the information, the first line contains some strange characters : �<�}�U1.
Code is as follows:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void createCalendar(char filename[]) {
FILE *cptr;
cptr = fopen(filename, "w");
char dates[177/sizeof(char)] = "";
for(int i = 1; i < 32; i++) {
char strtowrite[7/sizeof(char)] = "";
sprintf(strtowrite, "%d - \n", i);
strcat(dates, strtowrite);
}
fprintf(cptr, "%s", dates);
fclose(cptr);
}
void addToDay(char filename[], int day, char event[]) {
FILE *cptr;
cptr = fopen(filename, "r");
char *line = NULL;
size_t len = 0;
ssize_t read;
char dates[177/sizeof(char) + strlen(event)/sizeof(char)];
int i = 1;
while ((read = getline(&line, &len, cptr)) != -1) {
if (i==day) {
char strtowrite[7/sizeof(char) + strlen(event)/sizeof(char)];
sprintf(strtowrite, "%d - %s\n", i, event);
strcat(dates, strtowrite);
}
else {
strcat(dates, line);
}
i += 1;
}
printf("%s", dates);
fclose(cptr);
cptr = fopen(filename, "w");
fprintf(cptr, "%s", dates);
fclose(cptr);
}
int main() {
createCalendar("january");
addToDay("january", 12, "event");
}
and the first line of output is: í¬_<89>lU1 - (in the file)
Try this
char dates[177/sizeof(char) + strlen(event)/sizeof(char)] = {0};
in your addToDay function when declaring the dates variable. I think that you do not set the memory there, so there might be some junk in that memory location.
So i am trying to determine number of words from n strings.The problem I have is that the when I read the number of the strings from the file it somehow count as a string I guess.I am trying to get rid of the first line of the output but can't tell how.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int numar_cuvinte(char *propozitie, char *copie, int numar_propozitii, FILE *f)
{
fgets(propozitie,49,f);
strcpy(copie,propozitie);
char *delimitatori = " ";
char *token = strtok(copie,delimitatori);
int numar_cuvinte = 0;
while(token!=NULL)
{
numar_cuvinte++;
token = strtok(NULL,delimitatori);
}
return numar_cuvinte;
}
int main()
{
FILE *f;
char*name_file = "in.txt";
f=fopen(name_file,"r");
if(f == NULL)
printf("Can't oppen %s",name_file);
int nr_strings;;
fscanf(f,"%d",&nr_strings);
char *propozitie = (char*)malloc(50*sizeof(char));
char *copie = (char*)malloc(50*sizeof(char));
for(int i = 0 ; i <= nr_strings ; i++)
printf("String : %s has %d words \n\n",propozitie,numar_cuvinte(propozitie,copie,nr_strings,f));
free(propozitie);
free(copie);
fclose(f);
return 0;
}
So, what I am trying to do is initialize an unsigned integer buffer and also using a file pointer(FILE *fp) to read from a file and store the contents of the file in the above mentioned buffer
The thing is that the problem doesn't occur when I don't use malloc() and define the buffer as an unsigned integer array instead
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 10000
void main()
{
unsigned int i = 0;
unsigned int *buffer = (unsigned int*)malloc(sizeof(unsigned int)*SIZE);
unsigned int c;
unsigned int length = 0;
FILE *fp = fopen("testfn.c", "r");
if (fp == NULL) {
printf("\nFile not found.\nExiting...");
exit(1);
}
while ((c = fgetc(fp)) != EOF)
{
buffer[i] = c;
++i;
}
length = i;
printf("\nNumber of elements= %d\n", length);
for (i = 0; i <= length; ++i)
printf("%c ", buffer[i]);
fclose(fp);
}
The expected output are the contents of the file stored as integers and printed on the screen.
What I am receiving is a segmentation fault and no output.
I am trying to create a thread and read from stdin inside the thread. In main() have dynamically allocated memory to a 2d array based on the size given as user input. In the thread I am reading from stdin and splitting it using strtok and adding it into the 2d array. I am not sure why there is a segmentation fault, searched SO and I seem to have handled all the cases related to strtok.
This is the program -
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
int dimB;
int dimA;
char** buffer;
char* temp;
void *thread(void *threadid){
char *buf;//[30] = {};
size_t len = 0;
ssize_t read;
char *line = NULL;
char *each;
printf("Hello World!.\n");
while ((read = getline(&line, &len, stdin)) != -1) {
printf("%s || \n", line);
each = strtok(line," ,()");
printf("************************%s ", each);
while(each != NULL){
buf = each;
strcpy(buffer[0][0], buf);
printf("%s", buf);
each = strtok(NULL," ,()");
}
}
pthread_exit(NULL);
}
int main (int argc, char *argv[])
{
pthread_t tidMpr;
long r;
int i;
dimB = atoi(argv[1]);
dimA = atoi(argv[2]);
pthread_t tidRdr[dimA];
buffer = malloc(dimA * sizeof(char*));
temp = malloc(dimA * dimB * sizeof(char));
for (i = 0; i < dimA; i++) {
buffer[i] = temp + (i * dimB);
}
//Create thread Thread
pthread_create(&tidMpr, NULL, thread, NULL);
free(temp);
free(buffer);
pthread_exit(NULL);
}
The 2d array memory allocation is from this question - How do I work with dynamic multi-dimensional arrays in C?.
I know I am writing everything to buffer[0][0], but that is so that I can store each in a buffer array buffer[0][1], buffer[0][2] later on based on some logic. But that shouldn't be a problem now right?
Also line is printing the correct value, whatever it is reading from stdin. So, probably strtok is the problem.
Another very similar program produces the desired output. This -
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
typedef struct { char action; int score; } Rules;
Rules rules[5] = {{'P',50}, {'L',20}, {'D',-10}, {'C',30}, {'S',40}};
int findScore(Rules* rules, char action){
int i;
for(i=0; i<5; i++){
if(rules[i].action == action)
return rules[i].score;
}
fprintf(stderr, "Action not present! Exiting...\n");
exit(EXIT_FAILURE);
}
int main(int argc, char *argv[]){
FILE *fp;
char inputTuple[30] = {};
char buf[30] = {};
char* oB;
oB = "(";
char* cB;
char* co = ",";
cB = ")";
fp = fopen(argv[1], "r");
int score;
char *each;
size_t len = 0;
ssize_t read;
char * line = NULL;
char *eacharray;
int u = 0;
char *outputTuple;
int pad = 0;
int g;
if (fp == NULL)
exit(EXIT_FAILURE);
while ((read = getline(&line, &len, fp)) != -1) {
each = strtok(line," ,()");
while(each != NULL){
if(u%3 == 0){
outputTuple = (char *) malloc(1 + strlen(each)+ strlen(oB) );
strcpy(outputTuple, oB);
strcat(outputTuple, each);
} else if(u%3 == 1){
char q = *each;
score = findScore(rules, q);
} else if(u%3 == 2){
char * str3 = (char *) malloc(1 + strlen(outputTuple)+ strlen(co) );
strcpy(str3, outputTuple);
strcat(str3, co);
char *str4 = (char *) malloc(1 + strlen(str3)+ strlen(each) );
strcpy(str4, str3);
strcat(str4, each);
for(pad = strlen(each); pad<15; pad++)
strcat(str4," ");
sprintf(buf, "%s,%d)\n", str4, score);
printf("%s", buf);
free(outputTuple);
free(str3);
free(str4);
}
each = strtok(NULL," ,()");
u++;
}
u = 0;
}
fclose(fp);
return 0;
}
Update :
strcpy(buffer[0][0], buf); seems to be the problem. When I comment it, it is producing the output. I dont understand why is that causing a problem.
Currently working on a concordance program in C. When I try to run the program though, I get an error.
This is my C program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
void print(char Table, int n) {
printf("%d: ", n+1); // Prints the table
}
int insert(const void *bb, const void *cc) {
return strcmp(*(const char **)bb, *(const char **)cc);
}
void empty(char *Table[]) {
strcat(Table,"NULL"); // Empties the table
}
int main(int argc, char *argv[]){
if(argc!=3){
printf("ERROR: Usage: concordance table_size"); // Errors due to not enough variables (Should be tablesize and file name)
} else {
FILE *fp; //This block opens the file user has inputted and makes the string "File_contents" set to the file's contecnts
fp = fopen(argv[2],"r");
char *file_contents;
long input_file_size;
fseek(fp, 0, SEEK_END);
input_file_size = ftell(fp);
rewind(fp);
file_contents = malloc((input_file_size + 1) * (sizeof(char)));
fread(file_contents, sizeof(char), input_file_size, fp);
fclose(fp);
file_contents[input_file_size] = 0;
char *word, *words[strlen(file_contents)/2+1];
int i, n;
for(i=0;file_contents[i];i++){
file_contents[i]=tolower(file_contents[i]); //Converts all words to lower case
}
i=0;
word = strtok(file_contents, " ,.-:;?!"); //Chars which signal end of word
while(word != NULL) {
words[i++] = word;
word = strtok(NULL, " ,.-:;?!");
}
n = i;
qsort(words, n, sizeof(*words), insert);
for(i=0; i<n; ++i){
print(words[i],i);
printf("%s\n", words[i]);
}
empty(words);
fclose(fp); // Closes open file
}
return 0;
}
And the following is the error I'm getting:
* glibc detected * concordance: double free or corruption (!prev): 0x0000000001060f010
Not sure what could be causing this error to happen. Any help on this would be great though.
You aren't calling fclose() twice. Which I suppose in turn might call free() internally. Remove the fclose() at the end of the program.
you are passing NULL as argument to strtok function. I think this may cause the problem