Markov chain (c code on windows fails) [closed] - c

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am trying to get work this piece of code from Kernighan's book The practice of programming on my workstation(windows 7 + vs2015 community edition)
I get a strange error.
void generate(int nwords) {
State *sp;
Suffix *suf;
char *prefix[NPREF];
char *w = NULL;
int i, nmatch;
for (i = 0; i < NPREF; i++)
prefix[i] = NONWORD;
for (i = 0; i < nwords; i++) {
sp = lookup(prefix, 0);
nmatch = 0;
for (suf = sp->suf; suf != NULL; suf = suf->next) {
if (rand() % ++nmatch == 0) {
w = suf->word;
}
if (nmatch == 0)
printf("internal error: no suffix %d %s", i, prefix[0]);
if (strcmp(w, NONWORD) == 0)
break;
printf("%s ", w);
memmove(prefix, prefix + 1, (NPREF - 1) * sizeof(prefix[0]));
prefix[NPREF - 1] = w;
}
}
}
for (suf = sp->suf; suf != NULL; suf = suf->next)
Unhandled exception at 0x000000013F5C1564 in CompareCandCsharp.exe:
0xC0000005: Access violation reading location 0x0000000000000010.
My implementation is similar to described here - Working with arrays and reading text files
Seems algorithm works - but on my computer it fails. I can't find mindfull porpose for this. Could you please give your suggestions.

After several hours of debugging I have found a small mistake in expected method.
for (suf = sp->suf; suf != NULL; suf = suf->next) {
if (rand() % ++nmatch == 0) {
w = suf->word;
}
There is no bracket after if in this line so all other code in method try set w many times and of course it leads to memory errors =). Thanx for minusing my question before reading it =))

Related

Why is my %d specifier putting the "-" after the number? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last month.
Improve this question
I am trying to make a C implementation of the printf function. Why does my %d specifier return
+2048 - 0 - 1337-!
instead of
-2048 - 0 - -1337!
when I run
int main() {
int ret_val = my_printf("%d - %d - %d!\n", 2048, 0, -1337);
return ret_val;
}
This is my %d specifier code
{
int value = va_arg(args, int);
char buffer[32];
int index = 0;
if (value < 0)
{ //Repair this
buffer[index++] = '-';
value = -value;
}
if (value == 0)
{
buffer[index++] = '0';
}
else
{
while (value > 0)
{
buffer[index++] = '0' + (value % 10);
value /= 10;
}
}
for (int i = 0; i < index / 2; i++)
{
char temp = buffer[i];
buffer[i] = buffer[index - i - 1];
buffer[index - i - 1] = temp;
}
write(1, buffer, index);
size += index;
break;
}
I have tried switching these 2 lines with each
The reason for the symptoms reported by the OP has been quickly and correctly addressed by #EricPostpischil in the comments section.
The problem with writing code from the wrong perspective is that one winds up writing far too much code. Then, lost in the fog of verbose code, patches and bandages are applied that don't quite fulfil the need.
Simply fill the 32-byte buffer from right to left, prefix the minus sign if necessary, and write the correct number of bytes to the output.
int val = va_arg( args, int );
int absVal = abs(val);
char buf[ 32 ];
int i = sizeof buf;
do buf[--i] = (char)('0' + (absVal%10)); while((absVal/= 10) > 0);
if( val < 0 )
buf[--i] = '-';
write( 1, buf + i, sizeof buf - i );
No muss, no fuss trying to reverse the array... or most of it...

Obviously declared variable is considered undeclared [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have the following code* inside an if else {} code block but the GCC compiler throws me this error:
hw2b.c: In function `printSymbolK':
hw2b.c:26: parse error before `int'
hw2b.c:27: `w' undeclared (first use in this function)
hw2b.c:27: (Each undeclared identifier is reported only once
hw2b.c:27: for each function it appears in.)
*
int w = 0;
for(w = 4; w < i; w++) {
printf(" ");
}
Can someone tell me what i'm missing here? The w variable is declared and initialized inside the if else block but it says it isn't. Any ideas?
EDIT: You were right, i only copied a small piece of my program. Here is the full code:
#include <stdio.h>
/*
* The printSymbolK function accepts a
* natural number (N > 3) and prints the
* symbol K to the console according to certain
* specifications.
*/
void printSymbolK(int N) {
int i = 0,k=0;
int katoAkeraioMeros = N/2; // to apotelesma tou pilikou tha strogkilopoihtei pros ta kato dinontas mas to kato akeraio meros tou N/2
char star = '*';
for(i = 0;i < N; i++) {
if( i < katoAkeraioMeros) { // katoAkeraioMeros - i+1 = posa tha einai apo pano
int res = katoAkeraioMeros - 1; // poses fores tha trexei i epanalipsi
int l = 0;
printf("%c",star);
for(l = i;l < res;l++) {
printf(" ");
}
printf("%c\n",star);
} else if(i+1 == katoAkeraioMeros) {
printf("%c%c\n",star,star);
} else if(i > katoAkeraioMeros) { // auxise to space kata 1 gia kathe i apo edo kai pera
printf("%c",star);
int w = 0;
for(w = 4; w < i; w++) {
printf(" ");
}
printf("%c\n",star);
} else {
printf("%c %c\n",star,star);
}
}
}
int main() {
// Stelios Papamichail 4020
int n = 0;
do {
scanf("%d",&n);
printf("\n\n");
} while(n <= 3);
printSymbolK(n);
return 0;
}
the first error says it all:
hw2b.c:26: parse error before `int'
So something triggered a syntax error before the int token.
you shouldn't worry about further errors. at this point the parser is confused and thinks you're using w whereas you're trying to declare it (compilers don't stop at the first error so you can fix several errors at once, but sometimes that backfires, and sometimes they stop at some error, and when you fix it, you get more errors... compiler does its best with invalid code)
Just fix the first error, and retry.
Without seeing the full code, I would guess your using an older C compiler (C89) and you have code that is neither variable definition nor declarations above 'int w = 0;'.

Add letter if it's duplicate C [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I work on playfair cipher and I have one problem.
I need to add letter X in my string if the next letter it's duplicate.
Example before: HELLOWORLD
separe the string in 2 pairs (HE LL OW OR LD) and if it's duplicate add X. (I need to add X only if the pair is duplicate.
After: HE LX LO WO RL D -> HELXLOWORLD
My code:
for (j = 0, i = 0; i < len_text; i++, j++) {
if (i % 2 == 0) {
if (my_text[i] == my_text[i+1]) {
text_x[j] = my_text[i];
i++;
text_x[j+1] = 'X';
j++;
}
else {
text_x[j] = my_text[i];
}
}
else if (i % 2 != 0) {
text_x[j] = text[i];
}
}
My code don't works normally. Can you help me? Thank you.
If I'm understanding your problem correctly, you could do something like this. The way you're currently doing it looks like it could potentially go out of bounds with i. Make sure that text_x is a buffer big enough to hold these extra chars you're inserting (i.e. len_text + len_text / 2 at max).
for (j = 0, i = 0; i < len_text - 1; i+=2, j+=2) {
text_x[j] = my_text[i];
if (my_text[i] == my_text[i+1]) {
text_x[j+1] = 'X';
j++;
}
text_x[j+1] = my_text[i+1];
}

While loop doesn't initialize [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I've got a problem. Here is a function that processes the width of a wide-string. My program is entering an infinite loop after BREAKPOINT 1. What's wrong with my loop?
static void ft_wstr_width(void)
{
wchar_t *temp;
size_t delta;
size_t len;
size_t i;
wint_t wc;
len = ft_wstrlen(g_ws);
delta = (size_t)g_fmt.width - ft_wstrsize(g_ws);
printf("(%d %zd)\n", g_fmt.width, ft_wstrsize(g_ws));
temp = (wchar_t *)malloc(sizeof(wchar_t) * (len + delta + 1));
temp[len + delta] = L'\0';
if (g_fmt.flags[0])
{
wc = (QWSZ ? L'0' : L' ');
i = 0;
while (i < delta);
{
temp[i] = wc;
++i;
}
ft_wcopy(temp, g_ws, delta, len);
}
else
{
printf("[bp0]"); getchar(); // BREAKPOINT 0
ft_wcopy(temp, g_ws, 0, len);
i = len;
printf("[bp1]"); getchar(); // BREAKPOINT 1
while (i < len + delta);
{
printf("[bp2]"); getchar(); // BREAKPOINT 2
temp[i] = L' ';
++i;
}
}
printf("[bp3]"); getchar(); // BREAKPOINT 3
free(g_ws);
g_ws = temp;
}
-----UBUNTU TERMINAL OUTPUT-----
stanislav:gh_ft_printf >>: ./a.out
(15 3)
[bp0]
[bp1] No reaction here (program keeps running) and
^C <---- I have to kill the process with Ctrl+C
while (i < len + delta);
Semi-colon.

free(ptr) crashes sometimes, pointer is always valid [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am trying to create some streams of bytes, dynamically allocated, and perform a copy of them in some other place. My code is this (earlier i didn`t type from a pc :) ):
void construct_cypherstreams(uint8_t * stream, int key_length, int stream_length, uint8_t ** encr_streams, int * bytes_in_stream) {
// chyperstream = the stream formed of every ith byte
uint8_t * cypherstream;
int length;
length = stream_length / key_length + 1;
// each byte of the key can have values
// between 0 and 256
int i = 0;
int num_added = 0;
for (int k = 0; k < key_length; k++) {
printf("\n%s %d\n", "iteration", k);
i = k; num_added = 0;
cypherstream = (uint8_t *)malloc(length * sizeof (char));
if (cypherstream == NULL) {
printf("%s\n", "could not allocate");
exit(1);
}
else {
printf("%s\n", "succesfully allocated");
}
while (i < stream_length) {
// construct cypherstream
cypherstream[num_added] = stream[i];
num_added++;
i += key_length;
}
printf("\n%s\n", "created cypherstream:");
for (int m = 0; m < num_added; m++) {
printf("%X", cypherstream[m]);
}
printf("\n");
printf("%s\n", "making deep copy...");
encr_streams[k] = (uint8_t *)malloc(num_added * sizeof(char));
// perform deep copy of characters
for (int n = 0; n < num_added; n++) {
encr_streams[k][n] = cypherstream[n];
}
printf("%s\n", "done making deep copy");
free(cypherstream);
printf("%s\n", "succesfully freed");
printf("%s %d\n", "position:", k);
printf("%s %d\n", "num_added:", num_added);
bytes_in_stream[k] = num_added;
printf("%s\n", "iteration ended");
}
}
And I call it like this:
uint8_t ** encr_streams;
int * bytes_in_stream;
encr_streams = (uint8_t **)malloc(key_length * sizeof **encr_streams);
bytes_in_stream = (int *)malloc(key_length * sizeof *bytes_in_stream);
construct_cypherstreams(stream, key_length, stream_length, encr_streams, bytes_in_stream);
Now my program sometimes runs, sometimes crashes.
I am stuck here for the moment and I could really use some help.
Compiler: msvc
Thanks
encr_streams = (uint8_t **)malloc(key_length * sizeof **encr_streams);
just looks wrong. I think it should be
encr_streams = malloc(key_length * sizeof *encr_streams);
because you seem to intend to allocate an array of pointers to uint8_t. Then you probably also have to initialize the elements of that array by something.
This is a case of heap corruption as you are trying to overwrite some dynamically allocated memory.
If you program on Linux, run your code under the valgrind memory debugger:
http://valgrind.org/docs/manual/quick-start.html
For Windows... you may want to try MS AppVerifier though I haven't used it for years and forgot almost everything about it :-(
How to use Microsoft Application Verifier

Resources