SImple C program with array is not printing proper output - c

I wrote this incredibly stupid code
#include <stdio.h>
main(){
int new[10], i;
for(i=1; i<=10; ++i){
new[i] = 0;
}
for(i=1;i<=10; ++i)
{
printf("%d", new[i]);
}
}
I compiled this using GCC on Xubuntu and then did the ./a.out. The cursor is just blinking resulting in no output. The same is the case when tried to debug with gdb. It runs and then stays with the blinking cursor.
Any help?

C arrays are 0 indexed - your program writes outside the boundaries of the new array, so it causes undefined behaviour. In this case, you probably are overwriting the i variable, so you end up with an infinite loop. You need to change your loops:
for (i = 0; i < 10; i++)
{
new[i] = 0;
}
and:
for (i = 0; i < 10; i++)
{
printf("%d", i);
}

you need to have a new line character to see the output , or flush the stdout otherwise sometimes it doesn't print, or it will be combined with the next line... try:
printf("%d\n", new[i]);
also, set your for loop from 0 to 9

int new[10] - Here new array can store 10 elements of type integer. You can access these elements from 0th to 9th index of array. Accessing beyond 9th index is undefined behavior.

Related

Segfault when fusing double for-loop

I have read this post on how to fuse a loop. The goal is to fuse my double for loop in order to parallelize it with OpenMP. The reason why I don't use collapse(2) is because the inner loop has dependencies on the outer one. I have also read this relevant post.
My problem though, is that when I fuse my loop I get a Segmentation Fault error and that sounds pretty fuzzy. I am pretty sure I am making the right conversion. Unfortunately there is no way I can provide a reproducible - minimal example as my program has a ton of functions where they call one another. Here is my initial loop though:
for(int i=0; i<size; i++)
{
int counter = 0;
for(int j=0; j<size; j++)
{
if (i==j)
continue;
if(arr[size * i + j])
{
graph->nodes[i]->degree++;
graph->nodes[i]->neighbours[counter] = (Node*)malloc(sizeof(Node));
graph->nodes[i]->neighbours[counter] = graph->nodes[j];
counter++;
}
}
}
where graph is a pointer to Struct and graph->nodes is an array of pointers to the graph's nodes. Same goes for graph->nodes[i]->neighbours. An array of pointers (pointed to by a pointer pointed to by another pointer - sorry).
As you can see the fact that I am using the counter variablethat restricts me from using #pragma omp parallel for collapse(2). Below you can see my converted loop:
for(int n=0; n<size*size; n++)
{
int i = n / size;
int j = n % size;
int counter = 0;
for(int j=0; j<size; j++)
{
if (i==j)
continue;
if(arr[size * i + j])
{
graph->nodes[i]->degree++;
graph->nodes[i]->neighbours[counter] = (Node*)malloc(sizeof(Node));
graph->nodes[i]->neighbours[counter] = graph->nodes[j];
counter++;
}
}
}
I have tried debugging with valgrind and what's ultra weird is that the Segmentation Fault does not appear to be on these specific lines, although it happens only when I make the loop conversion.
Mini disclaimer: As you may guess, because of these pointer to pointer to pointer variables I use lots of mallocs.
I don't expect you to get the same error with the code that I have posted that is why my question is more of a general one: How could theoretically a loop fusion cause a segfault error?
I think in your converted loop you got i and j mixed up.
It should be int i = n % size;, not j.
n / size always equals 0.

C array problems... (Printing and defining)

Just writing some code to sort an array using bubble sort, but right at the start I couldn't even define an array and print it.
Code:
#include <stdio.h>
int main () {
int test[] = {9,9,9,9,9}; //define array
test[2] = 3;
bool checker = false; //is it sorted?
int i = 0;
for(int i = 0; i<=4; i++) //set random numbers for array
{
int g;
g = 4+i;
test[i] = g;
i++;
}
for (int i = 0; i <= 4; ++i ) //print array as normal
{
printf(", ", test[i]);
}
When executed it always outputs:
, , , ,
so the array is empty? or im printing it wrong? or something?
You are printing it wrong.
The line in which you are printing should read printf("%d, ", test[i]);
Also not that you have tagged the question as C++, but are using C related terms. Your #include <stdio.h> should be replaced by #include <iostream> and you should be using cout instead of printf for outputting data.
You have two problems in your code.
First, the initial 'for' loop uses 'i' as its counter variable, and your increment condition is 'i++'. That means 'i' automatically increments through each loop iteration; yet within the loop, you specify 'i++', meaning you will see the value of 'i' bumped twice with each pass. Eliminate the extraneous increment.
Second, you are printing the array incorrectly. You need to add a format qualifier such as '%d' to tell printf to use the first argument as a replacement for that specifier.
Lastly, you've indicated C++ for this code, but it really isn't. It's classic C.

C - not entering if even when he should

I'm seriously mad right now. I need to compare one string with second, when chars from second string can somehow create first string. Example
foo1 = bill
foo2 = boril
foo2 can create foo1, because it contains all the letters from foo1.
So there's my program:
secret = religion
lettersGuessed = religonvpst
for(i = 0; i < lenSecret; i++){
for(l = 0; l < lenGuessed; l++)
printf("A: %c, B: %c, C: %d\n", secret[i], lettersGuessed[l], count);
if(secret[i] == lettersGuessed[l]){
printf("HI\n");
count++;
break;
}
printf("C: %d\n", count);
}
But variable count always stays at 0. This is output from console:
http://pastebin.com/YrHiNLNi
As you can see right from beginning, when secret[i] == lettersGuessed[l] in if should return true(1), it returns false(0). What's wrong with this? Why it's not working?
It's because you don't have curly braces after your second for loop. If you don't wrap the block of code you want to iterate over with curly braces, only the code before the first semi-colon encountered will be executed. In this case, your second loop will iterate over the printf statement but nothing else. So variable l will always be equal to lenGuessed when the if statement is executed and no letter from the first word matches the last letter of the second word, therefore count is never incremented.
Ok, this is totaly crazy.
Code that I posted in my question was of course wrong, because I forget braces of second for loop. Small, but fatal mistake, I know, but I was seriously mad so I didn't pay attention. Anyway, the original code is following:
int isWordGuessed(char secret[], char lettersGuessed[]){
int i, l, count = 0;
int lenSecret = strlen(secret);
int lenGuessed = strlen(lettersGuessed);
for(i = 0; i < lenSecret; i++)
for(l = 0; l < lenGuessed; l++)
if(secret[i] == lettersGuessed[l]){
count++;
break;
}
return lenSecret == count ? 1 : 0;
}
At first, it was returning 0. After compiling it with different tools and launching it on two different OS (Windows 7 64-bit and Windows XP 32-bit) i was finaly able to get 1 from that function.
It seems like variable count had non-zero value while launching, so instead of int i, l, count; I wrote int i, l, count = 0;
Well, now I don't understand only one thing - why sometimes variables has non-zero value even when I never touched them. It happened to my before, but only in C, in other languages I never had such a problem.

Any reason why this "make a triangle loop" loops for longer than necessary

I have this function that will make an array of chars (ie a string) into a right triangle. It works but then it keeps going even after the array has stopped. So the output always has many extra lines of blank space.
and if the word is long enough random symbols will appear at the end of that blank space. This is probably because the blank space exited the arrays size of 100.
I dont know whats causeing this. I tried to set conditions to the counter and the printf that makes a new line but that just breaks the code entirely. I thought it was definitely the printf for new lines doing it but it doesnt seem like it now after trying that.
Does anyone see whats wrong?
Below is the remote function from my code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define clear system("cls")
#define pause system("pause")
void triangulate(char stringArray[]){
int i,j,len = 0;
int counter=0;
len=strlen(stringArray);//a function library function that returns the length
printf("\n");
for(i=1;i<=len;++i){
for(j=1;j<=i;++j){
printf("%c",stringArray[counter]);
counter++;
}
printf("\n");
}
printf("len:%i counter:%i",len, counter);
pause;
}//end triangulate()
This is wrong:
for(i=1;i<=len;++i) {
for(j=1;j<=i;++j) {
printf("%c",stringArray[counter]);
counter++;
}
printf("\n");
}
You can't increment counter so many times. Because of the nested loops, counter will access out of bounds positions - you are incrementing it towards a final value that is O(n^2) with relation to the string's length.
Let's consider the following simple case:
stringArray = "abc";
and see what happens in the two loops:
i = 1; j = 1; counter = 0;
i = 2; j = 1; counter = 1;
i = 2; j = 2; counter = 2;
i = 3; j = 1; counter = 3; // Undefined behaviour since stringArray[counter]
// is out of bounds
and so on (however, once you hit undefined behaviour, all bets are off and your program is free to do whatever it wants).

Prime numbers using Sieve of erastosthenes in C

I wrote the following program to display all prime numbers up to 150. It is not executing at all. what is so wrong with it?
# include <stdio.h>
int main(void)
{
int p[150], i, j;
for (i = 2; i < 150; i++)
p[i] = 0;
i = 2;
while (i < 150){
if (p[i] == 0)
printf("%i ", i);
for (j = 1; i*j <= 150; j++)
p[i*j] = 1;
i++;
}
return 0;
}
You're accessing p[i*j], which is beyond the valid [0-149] range. The condition i*j <= 150 will evaluate true when i*j is equal to 150, which is off-by-one. It should be i*j < 150.
The stdout stream is buffered. You need to flush at the end of your loop. Try adding a fflush(stdout).
Might be of less importance, but if you care about the resulting array (e.g.: wants to use it later), the value of p[2] is erroneously set to 1. However, your program would still print 2, but that's because your loop prints numbers before changing the value of p[i*j]. Concluding, numbers get printed correctly, but the values in the array are not entirely correct.
i*j <= 150 is incorrect, it should be i*j < 150, because the p array has elements from 0 to 149. The program gets stuck in an infinite loop because of this.
EDIT: The rest of this answer was incorrect, so I've removed it.
As a learning exeercise, try adding some printf's to learn what your program does.
Also bear in mind that, as jweyrich says, that printf without \n in it will not output anything until (possibly) the program exits.

Resources