alexander remus alexander remus - 2 months ago 8
C Question

Can I derefernce a local array passed into a function within the function?

I get a write access violation for the following:

void fun
(
char** s,
//EDIT_START
bool resize = false
//EDIT_END
)
{
//EDIT_START
if(resize)
*s = (char*)calloc(20, 1);
//EDIT_END
(*s)[0]='a';
}

int main(void)
{
char f1[10];
char* f2 = (char*)calloc(10, 1);
fun((char**)&f1);
fun(&f2);
return 0;
}


Culprit is

fun((char**)&f1);


Anything I'm missing here?

EDIT: "It looks like your post is mostly code; please add some more details." Disregard this edit please.

Answer

Thank you all for your answers and time. I came up with a way to do it and will answer the question myself for self reference.

void f(char** c1, bool resize)
{
    void* v1 = (void*)(*c1);
    cout << "changing memory at "<<v1<<"\n";

    if(resize)
        resize(c1); //defined elsewhere

    (*c1)[0]='a';
    (*c1)[0]='b';
    (*c1)[0]='c';
    (*c1)[0]='\0';
}

int
main
        (
        int argc,
        char *argv[]
        )
{

    char* s2 = (char*)calloc(4, 1);

    char s3[4];
    char* ps3 = s3;

    cout << "passing memory location ["<<(void*)&s2<<"] pointing to ["<<(void*)s2<<"]\n";
    f(&s2, true);
    cout << "passing memory location ["<<(void*)&s3<<"] pointing to ["<<(void*)s3<<"]\n";
    f((char**)&s3, false);
    cout << "passing memory location ["<<(void*)&ps3<<"] pointing to ["<<(void*)ps3<<"]\n";
    f((char**)&ps3, false);
}

Output:

passing memory location [006CFA20] pointing to [0076EAF0]
changing memory at 0076EAF0
passing memory location [006CFA18] pointing to [006CFA18]
changing memory at 006CFA80
passing memory location [006CFA1C] pointing to [006CFA18]
changing memory at 006CFA18

Turns out that s3 == &s3. Did not know that. Live and learn I guess.

Comments