I'm not really sure what happens here. The problem is that I get a segmentation fault at the last wprintf at line 66 in my code below.
I'm obviously missing something that is probably obvious for real programmers, but what?
Here's my code so far. Main starts at line 43 and the relevant function at line 29. The other functions are not important for this thread.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <string.h>
#include <wchar.h>
#define VER "0.1"
#define PROGNAME "SomeProgram"
const int WideMode=1;
void UserErrorExit(void) {
fputs("Incorrect number of parameters.\n", stderr);
fputs("Read the manual!\n\n", stderr);
fprintf(stderr,"man %s\n", PROGNAME);
exit(EXIT_FAILURE);
}
void MemoryErrorExit(void) {
fprintf(stderr, "Oops, seems like we are out of memory\n");
exit(EXIT_FAILURE);
}
void *WMalloc(char **mbs) {
size_t Len=mbstowcs(NULL, *mbs, 0);
wchar_t *newArray=malloc((Len+1)*sizeof(wchar_t));
if (newArray==NULL)
MemoryErrorExit();
Len=mbstowcs(newArray, *mbs, Len);
return (newArray);
}
int main(int argc, char *argv[])
{
setlocale(LC_ALL, ""); // Use system's locale.
fwide(stdout, WideMode); // Set standard output to wide character mode.
// Check user input. ——————————————————————————————————————————————————————————
if(argc<2 || argc>3)
UserErrorExit();
if(argc==2) {
if(strcmp(argv[1],"--version")==0) {
wprintf(L"Version: %s\n", VER);
return EXIT_SUCCESS;
}
else
UserErrorExit();
}
// ————————————————————————————————————————————————————————————————————————————
wchar_t *MyString;
MyString=WMalloc(&argv[1]);
wprintf(L"%s\n", *MyString);
free(MyString);
return EXIT_SUCCESS;
}
Compile:
Code:
gcc -Wall -Wextra -std=gnu99 "${Name}.c" -o "${Name}"
(The Name variable contains the program name)
What I'm trying to do:
The user enters the program name followed by two text strings.
One of those (at the moment) is supposed to be copied to a wide character string variable, ”MyString” using the WMalloc function (which by the way maybe needs another name – first it was only supposed to allocate memory for the string, then I enhanced its functionality and I should maybe have changed its name accordingly).
I guess the problem is the ”MyString=WMalloc(&argv[1]);” line (line 64), but I'm not sure how to make it right. My head is just spinning…
Running:
Code:
$ ./MallocInFunctionTest Johnny Rosenberg
Segmenteringsfel (minnesutskrift skapad)
$
The error message is in the language of my locale and means something like ”Segmentation fault (memory dump created)”.
gcc (Ubuntu 4.8.2-19ubuntu1) 4.8.2
Operating system: Ubuntu 14.04