1

This is a simple piece of code, but when I try to debug it in GDB I ran into problems; Here are my command line inputs:

gdb test
b main
info locals

the source code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
    char *str = "1111 1111\n";
    size_t n =2;
    FILE *outptr = fopen("target.txt","w");
    fwrite(str,strlen(str),1, outptr);
    char *str2 = "22222\n";
    fwrite(str2,strlen(str2),1, outptr);
    char *str3 = "3333\n";
    fwrite(str3,strlen(str3),1, outptr);
    char *str4 = "4444\n";
    fwrite(str4,strlen(str4),1, outptr);
    // char *str2 = "2222\n";
    // fwrite(str2,strlen(str2),3, outptr);
    fclose(outptr);
    return 1;
}

at the breakpoint of main, gdb shows all local variables already defined, but i have not step into the declarations yet. What troubles me more was that it seems the variables had non-null values coming from nowhere.

Thanks

Lucas Lu
  • 31
  • 3
  • 3
    Where is your code and where is your command line input? – Jabberwocky Mar 01 '18 at 07:52
  • 1
    They show up because once you have entered the function the local variables exist immediately. You are confusing compile time and run time. ANd what _exactly_ is the problem you ran into? Did your computer catch fire? – Jabberwocky Mar 01 '18 at 08:21
  • Thanks michael. It was my first post, it took me some time to figure out how to paste code into stackoverflow. – Lucas Lu Mar 02 '18 at 08:39
  • Now your question is a bit clearer. My previous comment stands. Once you have stepped into `main` all local variables exist, but they are not yet initialized, hence the values "coming from nowhere" they contain. These strange values don't come from nowhere, it's just the leftover content of the memory before the variables are assigned. – Jabberwocky Mar 02 '18 at 08:43
  • So, once the compiler finishes comping, the calling stack would have assigned bits to all local variables. GDB was giving me the values of the variables without checking if the variables have been initialized. Am I understanding you correctly, Michael? – Lucas Lu Mar 02 '18 at 08:49
  • More or less. What happens usually is this: when you call a function, the first thing the function does is reserving space for the local variables on the stack. That's the reason the variables exist immediately. Their initial content is whatever is in the stack. [This SO article](https://stackoverflow.com/questions/13244531/c-function-stack-layout) explains the details. – Jabberwocky Mar 02 '18 at 09:26
  • I have the same question :) – Rick Mar 31 '20 at 04:04

0 Answers0