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

View all comments

Show parent comment

1

u/Own_Unit_6170 Oct 29 '26

The heap is where I'd expect them to go, if they are being allocated and freed with procedure calls, otherwise static allocation somewhere else.

1

u/21Ali-ANinja69 Oct 29 '26

The heap is where global and manually managed memory lives. Storing globals on the stack means that they are automatically gone when you return from a function. Learn assembly and you'll understand why it's this way.

1

u/Own_Unit_6170 Oct 29 '26

I already know assembly. That's why I see a problem with storing variables on the stack. And in assembler, there is no heap, unless you want one (and usually you don't).

1

u/SmokeMuch7356 Oct 29 '26

So now we're down to only using registers.

Stack-based locals go all the way back to Fortran and Cobol; the auto storage class basically equates to stack management.

I'm just curious why you see it as a problem, when people like Backus and Thomspon and Wirth and Ritchie did not.

1

u/Own_Unit_6170 Oct 29 '26

The stack is typically small and very easily exhausted. That is a problem when you start misusing it for anything other than context switches and passing arguments.

1

u/Conscious_Support176 Oct 29 '26

This sounds simultaneously true and false. When you use the stack to store values that you are using to get to a result, all of those values are being used as arguments to the parts of your algorithm.

So if that’s what you mean by arguments, then yes it’s kind of a tautology, because values not being used to calculate your result are values that need to outlive the function so are going to be static or on the heap.

If it’s not, then how are you defining argument?

1

u/Own_Unit_6170 Oct 30 '26

An argument is passed from caller to callee and vice versa. This is in contrast to variables local to the called procedure and not see by the caller. Local variables do not belong on the stack. In addition, arguments that take up a lot of space should not be passed by value even if the language permits it.

Stack limitations are also an excellent reason to use loops or other iterations rather than recursive functions, despite the inexplicable popularity of recursion in ivory-tower CS classes.

1

u/21Ali-ANinja69 Oct 30 '26

This sounds possible in theory, but it also sounds like a lot of extra work for less performant code, since the heap is opaque to optimization. Embedded devs might actually riot if this somehow becomes the new norm.

Are you proposing that your C compiler should somehow automatically manage locals on the heap for you?

Also, recursion doesn't have to be an issue on the stack either. Tail call elimination allows you to repurpose stack frames on tail calls, rather than piling on another function call. The specification for Scheme mandates this, actually.

1

u/Own_Unit_6170 Oct 30 '26

This sounds possible in theory, but it also sounds like a lot of extra work for less performant code, since the heap is opaque to optimization.

The concept of a heap is specific to certain programming languages, not universal. It doesn’t exist in machine language. And it is aptly named, since it is a mess.

How would storing something elsewhere than on the stack require a lot of extra work?

Embedded devs might actually riot if this somehow becomes the new norm.

It depends on their religion.

Are you proposing that your C compiler should somehow automatically manage locals on the heap for you?

I am suggesting that compilers not attempt to allocate local variables on the stack. That’s not what the stack is for. A heap is purely a style of programming, but a stack has actual hardware constraints associated with it.

Also, recursion doesn't have to be an issue on the stack either. Tail call elimination allows you to repurpose stack frames on tail calls, rather than piling on another function call. The specification for Scheme mandates this, actually.

But we are talking about C, not Scheme. And a simple loop still has lower overhead, and need not touch the stack at all.

1

u/21Ali-ANinja69 Oct 30 '26

Why does it require more work? Because the compiler has to manage your memory for you, unless you want a runtime garbage collector. Locals on stack don't need to be explicitly deallocated after a function returns. If you store locals in the heap, they need to be explicilty destroyed after function return, otherwise you can smuggle the locals out of the function. The heap is a mess, yes. That is in fact why storing locals on the stack is so performant. There are guarantees that you can rely on for optimization. For one the Operating System has to allow you to access the heap to begin with, and well, there's a reason we check if malloc failed, but can just use locals without checking if they actually got allocated. Also you can reason about the stack at compile time, because it's well defined, the heap? Not so much. Fundamentally, you would need new Operatings System, and possibly even new hardware to store locals in the heap in a way that isn't just a hacky workaround circumventing decades of system built on the assumption of locals on the stack. Talking theory is important, but how should it practically work? How should the C compiler manage local variables on the heap? An important part of deeply held opinions on how things should be different is an idea on how to change things. So please. How should this work?

→ More replies

1

u/Conscious_Support176 Oct 31 '26

It’s unclear to me what you are trying to say. Local variables are passed as arguments if you use them as an input to any operation. If you are not see my previous comment.