I wrote three ways of passing arguments to a function that accepts argv argument.
- The first method of using string literals is the shortest and works fine, but gives me a deprecated warning as my test harness is cpp based:
error: conversion
from string literal to 'char *' is deprecated
[-Werror,-Wc++11-compat-deprecated-writable-strings]
The method using malloc works, though it's a tad bit longer.
The last method causes a seg fault. Can you help me figure out the mistake in the third method, where I create an array with predefined size and copy the contents? Why does it fail?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TEST3
int console_tester(int argc, char *argv[])
{
printf("argv: %s\n", argv[0]);
return 0;
}
int main()
{
#ifdef TEST1
// works, shortest, but gives compilation warnings
char *test_cmd[2] = {"hello1", "hello2"};
int result = console_tester(2, (char**)test_cmd);
#endif
// works, verbose
#ifdef TEST2
char *test_cmd[2];
test_cmd[0] = malloc(10);
test_cmd[1] = malloc(10);
memset(test_cmd[0], 0, 10);
memset(test_cmd[0], 1, 10);
memcpy(test_cmd[0], "hello1", sizeof("hello1"));
memcpy(test_cmd[1], "hello2", sizeof("hello2"));
int result = console_tester(2, (char**)test_cmd);
free(test_cmd[0]);
free(test_cmd[1]);
#endif
// crash and burn
#ifdef TEST3
char test_cmd[2][10];
memset(&test_cmd[0], 0, 10);
memset(&test_cmd[1], 0, 10);
memcpy(&test_cmd[0], "hello1", sizeof("hello1"));
memcpy(&test_cmd[1], "hello2", sizeof("hello2"));
int result = console_tester(2, (char**)test_cmd);
#endif
return 0;
}