Segfault in c program - c

I have a segmentation fault upon executing this program and all I know is that segfault is happening after two of the gets commands and after the next scanf command. I know gets isn't good command to use in here but my university is using it so... Here is the code of my main function and functions that program uses and I would appreciate if someone could said to me where the problem persists. The code is written in croatian but nothing really particular isnt said in there so don't mind that
My main program
#include <stdio.h>
#include "funkcije.h"
#define MAX 300
int main (void) {
char niz1[MAX+1], podniz[6], niz2[MAX+1];
int dulj_pod = 0, kontrola, duljina1 = 0, duljina2 = 0, kraj, brojac = 0, i;
float slicnost;
printf("Ucitaj prvi niz > ");
gets(niz1);
printf("Ucitaj drugi niz > ");
gets(niz2);
while (niz1[duljina1] != '\0')
duljina1++;
while (niz2[duljina2] != '\0')
duljina2++;
printf("Ucitaj duljinu podniza : ");
do {
scanf("%d", &dulj_pod);
} while ((dulj_pod < 2 || dulj_pod > 5) || (dulj_pod > duljina1 || dulj_pod > duljina2));
kraj = duljina1 - dulj_pod;
for (i=0; i<=kraj; i++) {
genPodniz (niz1, podniz, i, dulj_pod);
kontrola = sadrziPodniz (niz2, podniz);
if (kontrola == 1)
brojac++;
}
slicnost = (float)brojac / (kraj+1);
printf("Prvi niz : %s\nDrugi niz : %s\nDuljina podniza za usporedbu nizova : %d\n", niz1, niz2, dulj_pod);
printf("Slicnost nizova '%s' i '%s' iznosi %f.\n", niz1, niz2, slicnost);
return 0;
}'
And functions
#include "funkcije.h"
void genPodniz (char *niz, char *podNiz, int pocPozicija, int duljPodniz) {
int i, j=0;
for (i=0; i<duljPodniz; i++, j++) {
*(podNiz+j) = *(niz+pocPozicija+i);
}
*(podNiz+j) = '\0';
}
int sadrziPodniz (char *niz, char *podNiz) {
int kontrola, i = 0, j = 0, duljina1 = 0, duljina2 = 0, poz = 0;
while (*(niz+duljina1) != '\0')
duljina1++;
while (*(niz+duljina2) != '\0')
duljina2++;
while (j < duljina2) {
if (*(niz+i) == *(podNiz+j)) {
kontrola = 1;
i++;
j++;
}
else {
kontrola = 0;
j = 0;
++poz;
i = poz;
}
}
return kontrola;
}

First - find out how to run this code under a debugger. Then it'll just stop on the line where the segfault occurs, which should make it more-obvious what the problem is. Given that you're saying "segfault", it's probably safe to assume you're running some unix-variant, in which case, "gdb" is probably your debugger.
Second - a segfault is, maybe 90% of the time, due to overrunning the bounds of allocated memory. Since your program isn't allocating any memory with "malloc", that means you're writing past the end of one of your arrays. Chances are, one of your loops is running way too many times, and accessing past the end of an array.

Related

Random Bytes In C Output

I just wrote my first program in C and it is a cesarean shift implementation. It works as expected with short inputs, but sometimes produces seemingly random bytes at the and of the output and I cannot figure out why.
I have tried looking at the program in GDB, but just don't have enough experience yet to figure out exactly what is going wrong. I would love to know how one would go about figuring this out with a debugger like GDB.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void rot(char*, int);
char alphabet[27] = "abcdefghijklmnopqrstuvwxyz";
int main (int argc, char* argv[]) {
if (argc != 3) {
printf("Usage: %s [lowercase-text] [rotation-number]\n", argv[0]);
return 1;
} else {
rot(argv[1], atoi(argv[2]));
}
}
void rot (char* t, int r) {
char result[100];
for (int i = 0; i < strlen(t); i++) {
char* location = strchr(alphabet, t[i]);
result[i] = location ? alphabet[(location - alphabet + r) % strlen(alphabet)] : t[i];
}
printf("%s\n", result);
}
Here is the unexpected output. The actual rotation works fine but there are some unexpected bytes at the end.
michael#linux:~/Desktop$ ./rotation
Usage: ./rotation [lowercase-text] [rotation-number]
michael#linux:~/Desktop$ ./rotation rotations_are_cool 13
ebgngvbaf_ner_pbby��� (<- Why are these here ???)
Here was my attempt with GDB. I have not been able to identify the extra data tagging at the end. (full output # https://pastebin.com/uhWnj17e)
(gdb) break *rot+260
Breakpoint 1 at 0x936: file ../rot.c, line 25.
(gdb) r rotations_are_cool 13
Starting program: /home/michael/Desktop/rotation rotations_are_cool 13
Breakpoint 1, 0x0000555555554936 in rot (
t=0x7fffffffe2d2 "rotations_are_cool", r=13) at ../rot.c:25
25 printf("%s\n", result);
(gdb) x/s $rbp-0x80
0x7fffffffdde0: "ebgngvbaf_ner_pbby\377\367\377\177"
This strange occurrence only happens around 50% of the time and happens more often with longer strings. Please help explain and eliminate this. Any other tips that would improve my code are also appreciated. Thanks a dozen!
The end of a string is recognized by the character '\0'.
So you could do it like this
char result[100];
int i;
for (i = 0; i < strlen(t); i++) {
char* location = strchr(alphabet, t[i]);
result[i] = location ? alphabet[(location - alphabet + r) % strlen(alphabet)] : t[i];
}
result[i] = '\0';
You also don't check, that result is large enough for the string, so you could allocate the needed memory dynamically
size_t len = strlen(t)
char *result = malloc(len + 1); /* +1 for terminating '\0' character */
if(result == NULL) {
/* Error allocating memory */
}
int i;
for (i = 0; i < len; i++) {
char* location = strchr(alphabet, t[i]);
result[i] = location ? alphabet[(location - alphabet + r) % strlen(alphabet)] : t[i];
}
result[i] = '\0';
printf("%s\n", result);
free(result);

Values displayed after realloc are weird

I called malloc and then I want to cut size in half using realloc when i display values of relocated malloc few numbers shows as 0, is that normal or I messed something up?
double main()
{
double *test;
int size = 10;
int sizes;
int i = 0;
double value;
test = (double*)malloc(size*sizeof(double));
if(test == NULL)
{
printf("ERROR");
return 0;
}
else
{
printf("\nInsert values : \n");
for(i=0;i<=size;)
{
scanf("%lf",&*(test+i));
if(*(test+i)==0.0)
{
break;
}
if(i>=size)
{
size=size+2;
test = realloc(test, size*sizeof(double));
}
i++;
}
}
sizes=size/2;
test = realloc(test, sizes*sizeof(double));
printf("\nSaved values : \n");
for(i=0;i<size;i++)
{
printf("%lf\n",*(test+i));
}
}
I want to learn some coding so please tell me if and what I am doing wrong.
If I well understand you stop to read value at EOF or when the read value is 0, and 0 is not memorized, and when the read is done you want to reduce the allocates vector to the minimal size, in that case :
#include <stdlib.h>
#include <stdio.h>
int main()
{
int size = 10;
double *test = malloc(size*sizeof(double));
if(test == NULL)
{
printf("ERROR");
return 0;
}
else
{
int i = 0;
double value;
printf("\nInsert values : \n");
while ((scanf("%lf",&value) == 1) && (value != 0))
{
if (i >= size) /* == is enough */
{
size += 2; /* I add 2 entries as you */
test = realloc(test, size*sizeof(double));
}
test[i++] = value;
}
/* remove possible extra entry at the end */
if (i != size)
test = realloc(test, i*sizeof(double));
size = i;
printf("\nSaved values : \n");
for(i=0 ;i<size; ++i)
{
printf("%lf\n",test[i]);
}
free(test);
}
return 0;
}
Two issues here:
This
for(i=0;i<=size;)
makes this
scanf("%lf",&*(test+i));
scan into memory one element beyond the allocated memory on the last iteration before reallocating. Doing so invokes undefined behaviour. Already from now on anything may happen.
Those two lines
sizes=size/2;
test = realloc(test, sizes*sizeof(double));
shrink the valid memory to the half of its size, and then this loop
for(i=0;i<size;i++)
{
printf("%lf\n",*(test+i));
}
tries to read out the second half's value which just had been shrinked away. This half's memory is not valid any more. Trying to read it invokes undefined behaviour as well.
So to answer your question:
or i messed something up
Yes you did, namely by invoking undefined behaviour. Do not do that.

C stack corrupted for a string var

So as a part of a class project, I'm supposed to receive an input string from the user and to varies actions on it. For some reason, I get a stack corrupted error in the following code.
void main()
{
char cmd[80] = "", substr[81] = "", matrixName1[11], matrixName2[11], substrFrob[11] = "";
int start = 0, end = 0, cmdSort, i, j, prog = 0, row = 0, col, row1, row2, col1, col2, **matrix1, **matrix2, trace = 0, words, matrixNum = 0;
memset(matrixName1, 0, strlen(matrixName1)); //reseting variables
memset(matrixName2, 0, strlen(matrixName2));
printf_s("#");
fgets(cmd, sizeof(cmd), stdin);
words = wordCounter(cmd);
start = end;
stringCutter(substr, cmd, &start, &end);
while (1)
{
if (prog == 0) //sorting for command and number of args
{
if (!strcmp(substr, "exit") && words == 1) break;
else if (!strcmp(substr, "zeroes") && words == 4) cmdSort = 1;
else if (!strcmp(substr, "set") && words > 1) cmdSort = 2;
else if (!strcmp(substr, "echo") && words == 2) cmdSort = 3;
else if (!strcmp(substr, "frob") && words == 3) cmdSort = 4;
/* rest of the code*/
if (matrixName1[0] != 0) //freeing memory
{
for (i = 0; i < row1; i++)
free(matrix1[i]);
free(matrix1);
}
if (matrixName2[0] != 0)
{
for (i = 0; i < row2; i++)
free(matrix2[i]);
free(matrix2);
}
//system("cls");
//exit(0);
now as a part of the project we can't use any function within stdlib.h expect malloc and free. once I removed the exit(0), I started to receive an error when the user enters "exit" -
"Run time check Failure #2 stack around the variable 'substr' was corrupted"
but for the life of me, I can't find whats wrong.
thank in advence.
I couldn't check your code but it's likely that you are not allocating enough space for the char arrays. Trying to write to the char array that was not previously allocated can corrupt stack cookies hence the error.
If you had provided the full code I would try running it. In this case I can only guess :)
Edit: You might not be using the strlen right. You should be using "sizeof(char) * charcount " instead on memset calls.

Why does this C code (reading a file) crash upon exit (or file reallocation)?

The following code crashes right before upon program exit. I have tested it on both MSVS 2015 and GCC. The program is just assigning a VLA on the heap (read about it here if you want) and reads a file contents character by character and storing this character in the array. The program works perfectly well. It does and prints everything correctly. However upon exiting it crashes, or it ceases to respond.
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#define rows 8
#define columns 8
// allocate a VLA on the heap
void allocateVLArray(int x, int y, char(**ptr)[rows][columns])
{
*ptr = malloc(sizeof(char[rows][columns]));
assert(*ptr != NULL);
}
int main()
{
char (*grid)[rows][columns];
allocateVLArray(rows, columns, &grid);
if (grid) {
FILE *inputFile = fopen("test_fgetc.txt", "r");
if (inputFile) {
int x = 0, y = 0, length = 0;
char ch;
while((ch = (char)fgetc(inputFile)) != EOF) {
// CR and LF characters are captured together (if necessary) and counted as one char using '\n'
if (ch == '\n') {
x++; y = 0;
}
else {
*grid[x][y] = ch;
y++;
}
length++;
}
for (x = 0; x < rows; x++) {
for (y = 0; y < columns; y++) {
printf("%c", *grid[x][y]);
}
printf("\n");
}
printf("\nlength = %d\n", length);
}
}
free(grid);
return 0;
}
I've also noticed my constant memory usage has increased significantly, which means memory leaks. So It is probably a heap problem. Why is this happening and how can i fix it?
What is probably happening is that your "test_fgetc.txt" contains more than 64 characters, or more than 8 rows of characters. That would exhibit precisely the behavior that you are experiencing: it would appear to work, and it would crash on free().

Stack around the variable 'ch' was corrupted

I am in the process of writing a decipher algorithm for Vegenere Variant Cipher and ran into some C specific issues(I am not too familiar with C).
I get
"Run-Time Check Failure #2 - Stack around the variable 'ch' was corrupted" error.
If I understand the error right, ch is not available when I try to read/write to it(ch in this case represents a HEX value read from the text file, I have posted the code of the function below).
But, for the life of me, I can't figure out where it happens. I close the file way before the I exit the function(exception is thrown at the time I leave the function).
Can you take a look an let me know where I have it wrong? Thanks in advance.
P.S. I am tagging the question with C++ as well as it should pretty much be the same except, maybe, how we read the file in.
Anyways, my code below:
int getKeyLength(char *cipherTxtF){
int potKeyL = 1;
float maxFreq = 0.00;
int winKL = 1;
for (potKeyL = 1; potKeyL <= 13; potKeyL++)// loop that is going through each key size startig at 1 and ending at 13
{
unsigned char ch;
FILE *cipherTxtFi;
cipherTxtFi = fopen(cipherTxtF, "r");
int fileCharCount = 0;
int freqCounter[256] = { 0 };
int nThCharCount = 0;
while (fscanf(cipherTxtFi, "%02X", &ch) != EOF) {
if (ch != '\n') {
if (fileCharCount % potKeyL == 0){
int asciiInd = (int)ch;
freqCounter[asciiInd] += 1;
nThCharCount++;
}
}
fileCharCount++;
}
fclose(cipherTxtFi);
float frequenciesArray[256] = { 0 };
float sumq_iSq = 0;
int k;
for (k = 0; k < 256; k++){
frequenciesArray[k] = freqCounter[k] / (float)nThCharCount;
}
for (k = 0; k < 256; k++){
sumq_iSq += frequenciesArray[k] * frequenciesArray[k];
printf("%f \n", sumq_iSq);
}
if (maxFreq < sumq_iSq) {
maxFreq = sumq_iSq;
winKL = potKeyL;
}
}
return winKL;
}
You are trying to read an hexadecimal integer with fscanf() (format "%02X", where X means "integer in hex format") and store it into a char.
Unfortuantely fscanf() just receives the address of the char and doesn't know that you've not provided the address of an int. As int is larger than a char, the memory gets corrupted.
A solution could be:
int myhex;
while (fscanf(cipherTxtFi, "%02X", &myhex) != EOF) {
ch = myhex;
...

Resources