pointers - C Stack-Allocated String Scope -
for straight c , gcc, why doesn't pointed-to string corrupted here?
#include <stdio.h> int main(int argc, char *argv[]) { char* str_ptr = null; { //local scope-block char str[4]={0}; sprintf(str, "agh"); str_ptr = str; } printf("str_ptr: %s\n", str_ptr); getchar(); return 0; } |----output-----|
str_ptr: agh |--------------------|
here's a link above code compiled , executed using online compiler.
i understand if str string literal, str stored in bss ( static ), sprintf(ing) stack-allocated buffer, thought string buffer purely stack-based ( , address meaningless after leaving scope block )? understand may take additional stack allocations over-write memory @ given address, using recursive function until stack-overflow occurred, unable corrupt string pointed str_ptr.
fyi doing testing in vs2008 c project, although gcc seems exhibit same behavior.
most compiler sort of simple optimizations resulting in string still being in same place on stack. in other words, compiler allows stack grow store 'str'. doesn't shrink stack in scope of main, because not required so.
if want see result of saving address of variables on stack, call function.
#include <stdio.h> char * str_ptr = null; void onstack(void) { char str[4] = {0}; sprintf(str,"agh"); str_ptr = str; } int main(int argc, char *argv[]) { onstack(); int x = 0x61626364; printf("str_ptr: %s\n", str_ptr); printf("x:%i\n",x); getchar(); return 0; } with gcc -o0 -std=c99 strcorrupt.c random output on first printf. vary machine machine , architecture architecture.
Comments
Post a Comment