So when you call fopen() it modifies the copy to point somewhere else but it never changes the pointer in main().
Correct on all points. However, this isn't the problem. The code that kinghajj posted passes a pointer to a structure and calls fopen on a member of that structure. The changes will transfer back to the calling function. The real problem is a typical wild pointer access.
Code:
#include <stdio.h>
#include "ms.h"
bool register_script(Script *script, char *argv[])
{
/* script points to nothing predictable, dereferencing will likely segfault */
if( (script->file = fopen(argv[1],"r+")) == NULL)
{
return false;
}
return true;
}
int main(int argc, char *argv[])
{
Script *script; /* Declare a pointer -- OK */
if(argc == 1)
{
return 0;
}
if(!register_script(script,argv)) /* Use the wild pointer -- not OK */
{
printf("ERROR: Could not register script (wrong filename?)");
return 0;
}
return 0;
}
The solution is to either allocate memory to script in main, or use a stack variable instead.
Code:
#include <stdio.h>
#include "ms.h"
bool register_script(Script *script, char *argv[])
{
if( (script->file = fopen(argv[1],"r+")) == NULL)
{
return false;
}
return true;
}
int main(int argc, char *argv[])
{
Script *script;
if(argc == 1)
{
return 0;
}
script = malloc(sizeof *script);
if(script == NULL)
{
/* Handle allocation error */
}
if(!register_script(script,argv))
{
printf("ERROR: Could not register script (wrong filename?)");
free(script);
return 0;
}
free(script);
return 0;
}