sizeof(char)
is always 1.
So
myURL = (char *)malloc(sizeof(char));
allocates only one byte. That is not enough. You should always test malloc
against failure, and you should not cast the result of malloc
when coding in C (and in C++, better use std::string
or at least operator new
).
Of course you need to #include
all of <stdlib.h>
(for malloc
& getenv
& exit
...) and <stdio.h>
(for fopen
& perror
...) & <string.h>
(for strlen
, strcat
, strcpy
....)
And you are not sure that getenv("AppData")
succeeds by returning a non NULL
string.
So you should try:
char *appdata = getenv("AppData");
if (!appdata)
appdata="/some/default/path";
size_t appdatalen = strlen(appdata);
char* restpath= "/some/path.xx";
size_t restpathlen = strlen(restpath);
size_t fullpathlen = // 1 additional byte for terminating \0
appdatalen+restpathlen+1;
char *fullpath = malloc(fullpathlen);
if (!fullpath) { perror("malloc"); exit(EXIT_FAILURE); };
strcpy (fullpath, appdata);
strcat (fullpath, restpath);
FILE *myFile = fopen(fullpath, "r");
I'm using fullpath
, not myURL
, since fopen
cannot deal with URLs (like http://some.host.org/some/path
). If you need to deal with genuine URLs you need some HTTP client library like libcurl.
You might instead of a heap allocated fullpath
use a local buffer of PATH_MAX
characters. See also this thread.
Don't forget to compile with all warnings & debug info (e.g. with gcc -Wall -Wextra -g
if using GCC, and learn how to use the debugger (e.g. gdb
). Additional compiler options like -fsanitize=address
might be helpful. Addition debugging tools like valgrind also are helpful. Some of these tools might not be available on some operating systems (for beginners in C, I recommend using Linux).
Read about undefined behavior & buffer overflow.