jon doe
jon doe

Reputation: 544

Initializing strings in C

I've started to learn C and just learned that strings are just arrays of chars. I wanted to see values are in the strings at every given moment so I set a breakpoint in vscode, stepped through the execution, and looked at all the values.

int main()
{
    char a[4] = "foo";
    char b[4] = "bar";

    return 0;
}

I saw that before initializing the a[] array, there are already values in memory. screenshot of vscode while debugging.

My question is, what are those values? Why are they there? What do they represent?

Upvotes: 2

Views: 327

Answers (4)

serohrt
serohrt

Reputation: 71

When defining a value, it takes a part of memory that could have contained other numbers. It's basically those numbers being shown in your debug tab.

Upvotes: 2

mreza28
mreza28

Reputation: 1

When you create a new value like integers or arrays, system will give these values an address for saving its data on that address. There could be some data on that address for other applications and after closing that application, RAM won't remove them, so before initializing, you will see those data.

Upvotes: -1

Andrew Cina
Andrew Cina

Reputation: 154

Memory is memory, it could be uninitialized (aka filled with garbage) or it could be initialized with data.

In your case, when your program jumped to your main function a stack was created for it that would contain your local variables (your local variable being the char array you declared, basically a pointer to some place in memory). Before you initialized said pointers a and b to point at your string, they could have contained any old numbers and so trying to read the "string" at that address would give you more random garbage.

For example, if you wrote int a = 5; in your program and stepped through, you would similarly see that a might contain some random number before you assign it 5.

Upvotes: 0

arbitrary_A
arbitrary_A

Reputation: 373

When you first declare array or variable, it's assigned memory and that memory can contain some garbage values already, so it prints like this way

Garbage value can be anything, the language standard doesn't specify what it should be

Upvotes: 1

Related Questions