r/C_Programming • • Oct 27 '26

why can't I access values from an array?

I'm reading the Ansi C book, and I'm doing exercise 1.18

#include <stdio.h>
#define MAXLINE 1000

int myGetLine(char line[], int lim);
int myCopy(char to[], char from[], int lim);

int main() {
	int len;
	char line[MAXLINE];
	int toRemove = 0;

	while ((len = myGetLine(line, MAXLINE)) > 0) {
        //counts the trailing characters to remove
		for (int i = len - 1; i > 0 && (line[i] == ' ' || line[i] == '\t' || line[i] == '\n'); --i)
			++toRemove;
		int new_size = len - toRemove + 1;// +1 for the '\0'
		char to[new_size];// I guess this doesn't matter. Or it's just a piece of the puzzle. I need to limit copying
				  // in my copy method too.
        //printf("new_size: %d\n", new_size);
		int to_len = myCopy(to, line, new_size);
        //printf("%s\n", to);
        toRemove = 0;    
	}
	return 0;
}

int myGetLine(char s[], int lim) {
	int i, c;
	for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
		s[i] = c;
	if (c == '\n') {
		s[i] = c;
		++i;
	}
	s[i] = '\0';
	return i-1;
	}
//myCopy isn't working right now, after that I changed the while condition
//I need to add the \0
int myCopy(char to[], char from[], int lim) {
    int i = 0;
    char c = from[1];
    putchar(c);
    //printf("from[i]: %s", to);
    //printf("to[i]: %s, from[i]: %s", to[i], from[i]);
    while ((i < lim && (to[i] = from[i]) != '\0'));
        i++;
    to[i] = '\0';
    return i;
}

So I'm pretty much reusing the getLine from the book and I based my code on the code in the book, but I made changes to myCopy. The task is to remove any trailing spaces or tabs, so I thought that I could make a new copy and where the trailing whitespace starts, I'll just not copy that into my edited string. So I'm going through the array backwards, counting whitespace, calculating the new array size, then I want to create the edited array, but it's not working! So I tried to debug and I can't even putchar an element from the original I'm copying from in the myCopy function. If I do it with the line array, then it works. But why does it not work in the myCopy function? I just have no clue as to what's wrong.

I did manage to solve the exercise in a different way, but I really want to know why this is happening.

5 Upvotes

63 comments sorted by

35

u/mjmvideos Oct 27 '26

Run it in the debugger. Add a breakpoint in your function, step through looking at values of things. See where it goes wrong.

19

u/ForgedIronMadeIt Oct 27 '26

Being able to successfully use the debugger is probably one of the most important skills someone can learn in any programming environment and yet it isn't taught at all.

8

u/kayne_21 Oct 27 '26

most important skills someone can learn in any programming environment and yet it isn't taught at all.

My school teaches it as part of DSA. We had a lab for using the debugger specifically, a 50/200 point section of our midterm just debugging, with clues from the debugger to follow to find the bug. On top of this, we're required to write failure reports for our weekly programming homework every week which relies on data from the debugger for a failed unit test in order to get homework credit.

1

u/ForgedIronMadeIt Oct 27 '26

That's awesome. I feel like troubleshooting and debugging should be its own separate class in the degree -- I've probably spent at least a third of my time as a professional trying to figure out what happened and why. Staring at reams of logs (or worse, far too few logs) and then working the problem backwards is one skill, but being able to use the debugger's full range of capabilities is another. I get a lot of value out of conditional breakpoints, remote debugging, and everything else that it can do.

1

u/kayne_21 Oct 27 '26

I feel like troubleshooting and debugging should be its own separate class in the degree

I don't know about how tight CS is, I'm majoring in Computer Engineering. We really don't have room in my program for any more classes without dropping something else. We already have very few free electives.

1

u/mjmvideos Oct 28 '26

I feel like it ought to be an integral part of anyone’s first exposure to programming.

1

u/Sleezebag 27d ago

thank you. I tried to learn gdb, but it was a bit difficult for me. I'll invest some more time!

1

u/SRART25 27d ago

https://nostarch.com/debugging.htm And https://www.goodreads.com/book/show/3938178-debugging One teaches you to use the tools, the other teaches you how to organize and systematically debug.

2

u/Sleezebag 26d ago

wow, thank you! I definitely feel I haven't spent enough time on learning how to debug

21

u/SmokeMuch7356 Oct 27 '26 edited Oct 28 '26

I'm assuming "doesn't work" means the program is hanging. I'm making that assumption based on this:

 while ((i < lim && (to[i] = from[i]) != '\0'));
   i++;                                        ^
                                               |
                                          remove this

This falls into an infinite loop because i is never being updated.

In the future, please define "doesn't work." How doesn't it work? Is it crashing? Is it hanging? Is it giving garbage output? That's important information we need to help you figure out the problem.

1

u/Sleezebag 27d ago

thank you for you reply! Sorry for answering so late. That did indeed fix most of it. I will be more specific about what it means that it does not work in the future.

I do have a question though. putchar comes before the while loop in the code. Why wasn't I able to output a character from the array that I'm copying from? I'm thinking that putchar is evaluated before the execution even gets to the faulty loop.

1

u/SmokeMuch7356 27d ago

Could that character have been whitespace or a non-printing character?

One way to be sure would be to output it both as a char and an int:

printf( "c = '%c' (%d)\n", c, c );

To look at the whole thing you could do:

for( int i = 0; from[i]; i++ )
  printf( "from[%d] = '%c' (%d)\n",
    i, from[i], from[i] );

2

u/gm310509 Oct 28 '26

On my phone your "pointer" is wild - it looks like it is pointing at the assignment operator, but I am assuming you mean the ; that is terminating the while loop without doing anything with i.

I assume the code formatting works better on the PC.

Totally agree on your "it doesn't work" comments.

15

u/ShotSquare9099 Oct 27 '26 edited 27d ago

You should always use { … }. even if you are just putting one statement in there. It would have made it obvious what is wrong.

2

u/Sleezebag 27d ago

I do agree! I guess I thought since the authors of Ansi C wrote the code like that, that it was idiomatic in C. Thank you for your advice!

1

u/ShotSquare9099 27d ago

Being explicit is a good thing when writing code. Good luck!

1

u/Sleezebag 26d ago

thank you!

0

u/Wertbon1789 Oct 28 '26

I would carve out the case of an if statement, but for while and for I would always add curly braces. The case that you want one statement executed and nothing more isn't really happening in a loop, but early-return if statements are a thing, and I like to leave them out for this. Or even better, forget them entirely and make some sort of assert_return which itself just looks like a conditional with return value.

2

u/yel50 Oct 28 '26

the goto fail vulnerability is a great example of why brackets should always be used. no exceptions. code golfing one line here and there is a very junior mindset.

0

u/Wertbon1789 Oct 28 '26

I don't think this really guards you from a case of good-old bad code, missing review and bad test coverage. Yes, in this specific case it would have helped, but I don't think that's really that meaningful.

But, as I also said, I would prefer a assert_return, or here assert_goto, macro (which I've also seen before), because it's even more concise, and you kinda do DRRY with it, even though I don't care that much about that specifically. Also, you can partially enable the asserts to be abort conditions or add logs if they got hit, without touching the code itself, but with simple macro definitions. I think that's better, it's still clear to understand with some familiarity of how the codebase is supposed to work, and it's concise.

8

u/Illustrious_Trash117 Oct 27 '26

You made a semicolon after your while loop so i isnt incremented in the while loop. For readability i would also strongly advise against assignments in the condition of the loop. Make the assignment in the loop not in the condition.

1

u/Sleezebag 27d ago

Thank you. I had been staring at the code for so long, I just couldn't see it.

1

u/mjmvideos Oct 27 '26

Also, %c for characters. %s for a (null terminated) string.

1

u/Sleezebag 27d ago

thank you!

1

u/Own_Unit_6170 Oct 27 '26

You should be getting a fatal compile error, because you're defining to with a variable size, and the size has to be a constant.

If you don't need to preserve non-printing characters, you can just copy the string backwards, dropping anything less than a blank, and dropping blanks until you encounter the first character greater than a blank.

1

u/Sleezebag 27d ago

thank you!

2

u/SmokeMuch7356 Oct 27 '26

You should be getting a fatal compile error, because you're defining to with a variable size, and the size has to be a constant.

This has been legal since C99 - you can define an auto array with a size in a runtime variable, creating what's called a "variable-length" array (where "variable" means it can be a different size each time you create it, but once created its size is fixed).

static arrays cannot be VLAs, and VLAs cannot be declared with an initializer, but otherwise they work like any regular fixed-size array.

1

u/Own_Unit_6170 Oct 27 '26

That seems logical enough, but I just tried compiling it to see, and it generated a fatal error (MVC).

1

u/SmokeMuch7356 Oct 27 '26

Are you compiling as C99 or later? Or does MVC only support C89?

2

u/septum-funk Oct 28 '26

MSVC is a C++ compiler and only supports the C features that C++ has. VLAs have never been standard C++ therefore it does not

1

u/SmokeMuch7356 Oct 28 '26

Duh.  I knew that.  Really.

1

u/Own_Unit_6170 Oct 27 '26

It was set to "default," whatever version that is. I tried setting it to C17 but still got the error.

1

u/21Ali-ANinja69 Oct 27 '26

VLAs got removed from the stadard in C11, I think, but then C23 added them back in

1

u/Own_Unit_6170 Oct 27 '26

So it was broken twice. Do the people dreaming up these new versions ever work in actual production environments?

1

u/SmokeMuch7356 Oct 28 '26

VLAs were made optional in C11, so MVC may not support them.

Which is unfortunate, VLAs are useful.

1

u/21Ali-ANinja69 Oct 28 '26

Are they ever safe? It sounds like they can cause some nasty stack overflow nonsense if they get too big.

1

u/SmokeMuch7356 Oct 28 '26

Yeah, you need to do some sanity checking on the size before instantiating them.

Like everything else in C, it's assumed that the programmer is in the best position to know if such a check is necessary and is smart enough to write one if it is.

1

u/Own_Unit_6170 Oct 28 '26

Nothing should be stored on a stack except what is necessary to restore a caller's context.

1

u/21Ali-ANinja69 Oct 28 '26

I don't know how to interpret this comment. It seems a bit disconnected from what it's replying to.

→ More replies

1

u/evo_zorro 25d ago

VLA's were part of the C99 standard, but caused a bunch of issues. They're still in the C11 standard but as an OPTIONAL feature, so a compiler that doesn't support VLA's can be a perfectly valid C11 compiler. It's a bit of a sore point, but technically VLAs are allowed, but not guaranteed.

They were still optional in C18, and are now once more mandatory in C23. It's a right mess, and there's a lot of noise about it because some people really want VLAs, others don't care/don't use them, and the C99 behaviour was ill defined (sizeof behaviour and all that mess), so it took until C23 to make VLAs mandatory with definite behaviour in combination with offsetof and sizeof operators.

This is relevant because a lot of learners probably don't know the version they're using. GCC uses gnu23, clang only fully supports C99, with later versions being listed as partial. The point being: if you're learning, best avoided features that have patchy support across versions, and be explicit about the version you're assuming/using. If you're referencing K&R, arguably use C89, and be explicit about int returns and you should be ok

1

u/Illustrious_Trash117 Oct 27 '26

Thats called a variable length array and is fine in C as long as the array lives on the stack.

2

u/No_Choice_7629 Oct 27 '26

As others have already mentioned, you had an extra semicolon after while condition. Compiler can catch this with basic warnings enabled. Try:

-Wall -Wextra -Wpedantic.

myGetLine should return length, which is i, not i - 1 (K&R book p.30). Generally, length is the size of the array holding c-string minus null-terminator.

Trimming loop's condition should be i >= 0.

myCopy should take trimmed length as input, not size. There is not need to do an extra test for null: if destination array is len+1, then just copy until i == len, then null-terminate at len.

You could allocate copy array together with line array outside of the loop instead of using variable length (VLA), and make them the same size for simplicity.

1

u/evo_zorro 25d ago

For loop has ; ++i) and the end of the loop block: ++i; you'll end up only populating even offsets, your array is on stack which might (really need to check if this holds) mean it's memory is 0 initialised, but even if it isn't, if index 1 happens to be 0, your string ends there.

Your myCopy function starts with char c = from[1], the second element in the array, which your get line function never writes to. The length is going to be off, too. Because of your increment in the get line body of the loop, if i == MAX_LINE -1, you'll increment it to MAX_LINE in the last iteration, and write out of bounds (s[i] = '\0':).

This is just at first glance, on a phone screen, but that double increment in i just doesn't make sense