This line arr = (char*)malloc (2 * sizeof (char)); will allocate memory for 2 bytes only. But you are overwriting the memory by accessing the more 8 or more than 8 byes. If you access more than two byes means, it will give some unpredictable issue. In case you want more memory please follow the below code.
#define USER_SIZE 10
arr = (char*)malloc ( USER_SIZE * sizeof (char));
Assign the value in USER_SIZE macro and then allocate the memory as much as you want.
Example for 2D pointer ( 5 X 10 )
#define ROW 5
#define COLUMN 10
main()
{
unsigned char **p = NULL, colum = 0;
p = malloc ( ROW * sizeof ( unsigned char *) );
for (;colum< ROW; ++colum )
{
p[colum] = malloc (COLUMN * sizeof (unsigned char ));
}
}
Answer from mahendiran.b on Stack OverflowThis line arr = (char*)malloc (2 * sizeof (char)); will allocate memory for 2 bytes only. But you are overwriting the memory by accessing the more 8 or more than 8 byes. If you access more than two byes means, it will give some unpredictable issue. In case you want more memory please follow the below code.
#define USER_SIZE 10
arr = (char*)malloc ( USER_SIZE * sizeof (char));
Assign the value in USER_SIZE macro and then allocate the memory as much as you want.
Example for 2D pointer ( 5 X 10 )
#define ROW 5
#define COLUMN 10
main()
{
unsigned char **p = NULL, colum = 0;
p = malloc ( ROW * sizeof ( unsigned char *) );
for (;colum< ROW; ++colum )
{
p[colum] = malloc (COLUMN * sizeof (unsigned char ));
}
}
What you are doing is called buffer overflow by writing beyond the bounds of memory allocated by malloc call. The compiler doesn't do bounds checking (it assumes you know what you are doing, and you only pay for what you use) and allow you to compile and run. However, it will lead to undefined behaviour and your program may crash. You shouldn't rely on such behaviour.
You, the programmer, has to make sure that you don't do illegal memory access. You should not cast the result of malloc. Also, malloc can fail to allocate memory in which case it returns NULL, the null pointer, which you should take care of. You can combine the two statements into one.
int length = 8; // you can also use a macro
char *arr = malloc(length * sizeof *arr);
if(arr) {
// malloc call successful
// do stuff with arr
}
How can I create a character array in Java without a specified length? - Stack Overflow
Converting String[] array to dynamic char[] array in java? - Stack Overflow
C Dynamic char array - Stack Overflow
c - Creating a dynamic char array - Stack Overflow
Videos
If i have an array already full of data in a function:
char line [10] [128]
how would i dynamically allocate it so that i can use it in other functions?
Arrays must have a fixed length.
If your goal is to have a dynamically expansible list, consider a List instead. Everytime you add an item by add() method, it will grow dynamically whenever needed.
List<Character> chars = new ArrayList<>();
// ...
See also:
- Java Tutorials > Trail: Collections > The List Interface
You're probably looking for an ArrayList<Character>.
I think this is what you are looking for:
private static char[] stringArrayToCharArray (String[] words) {
int arrayLength = 0;
// Calculate the total size of the char array by adding the strings sizes
for (final String word : words)
arrayLength += word.length();
// Create the char array
char[] charArray = new char[arrayLength];
int arrayIndex = 0;
// Fill the array
for (final String word : words)
for (int i=0; i<word.length(); i++)
charArray[arrayIndex++] = word.charAt(i);
return charArray;
}
Here is how to use it:
String[] strs = {"test", "other"};
char[] chars = stringArrayToCharArray(strs);
What you want is to put every character within the string array into the char array????.
If it is, you have several ways to do this.
To avoid using an array list (increases its capacity dinamycally), you will have to know the amount of character inside each index of you string array, go through each index adding the amount of character to a variable that you previouly had declared (lets called sumChar), then create the char array with a capacity equals to sumChar char [] Carray=new chat[sumChar].
then do something like this int indexPos=0;
for (int i=0;i<names.length;i++)
{
for (int c=0;c<names[i];length;c++)
{
Carray[indexPos++]=names[i].charAt(c);
}
}
that's all, the code above I made it without tested it , so any problem feel free to ask
This:
realloc(input, (sizeof(char)));
is wrong. The realloc() function doesn't modify the given pointer (it can't!), it returns the new pointer. It can also fail, and return NULL.
Also, the second argument doesn't make any sense at all, it should be the new desired total size of the previously allocated buffer, but you're always passing (a very obscure) 1. It's not "grow this by this amount", it's the rather more low-level "attempt to grow this to this new size, and return the new location of the grown buffer".
Please read the documentation very carefully.
realloc(input, (sizeof(char)));
You are reallocating with same size (i.e 1 byte). It shoud be:
while((temp_c = getchar()) != '\n') {
realloc(input, (string_len + 1) * (sizeof(char)));
input[string_len++] = temp_c;
General malloc
man malloc may be helpful. malloc takes the minimum number of bytes you need of memory (i.e. malloc can choose to provide you more). So if you need exactly 10 elements in your char array, it may be best to simply allocate char* argv[10] as you have already done. However, this creates a container for exactly 10 char* which are not yet defined. Thus, for each char*, argv[0]...argv[9] you can define exactly what goes in there. For instance, if you want to malloc a string of size 200 for argv[0], you would use a statement as follows (notice that 200 can be held in either a constant or a variable):
argv[0] = malloc(200 * sizeof(char));
Generally, sizeof(char) == 1 byte, so this value is probably going to try to get 200 bytes. However, at this point you can modify argv[0] in any way you need to (i.e. strncpy, strncat, etc.).
Now, if you do not know how many arguments you may have, you can allocate your container on the fly. So instead of char* argv[10], you can try to allocate a char** argv. To do this, you would execute the following statement:
int SOME_SIZE = 1500 ; // Or some dynamic value read, etc.
char** argv = malloc(SOME_SIZE * sizeof(char*));
Often times the sizeof(char*) == 4 bytes on a 32-bit system (size of a typical pointer). Now you can use this chunk of memory, argv, in a similar way that has been done before. For ease of thinking about this, using malloc in this way allowed you to perform a relatively equivalent operation of char* argv[WITH_SOME_DYNAMIC_NUMBER]. Thus, you can manipulate this new container in a similar way as I have described above.
Remember though, when you are done with memory created by malloc, you must call free or else it will not be deallocated until the program terminates.
Your Problem
If I understand your question correctly, you have a flattened string which you want to turn into a string array for execve. I will work out a simple example trying to explain one of the many ways this can be done.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void someMethod()
{
char* argv[10];
char* path = getMyPath();
// Notice - this is a little messy and can/should be encapsulated away in another
// method for ease of use - this is to explicitly show, however, how this can work.
argv[9] = malloc((strlen(path) + strlen("--path=") + 1) * sizeof(char));
strncpy(argv[9], "--path=", strlen("--path="));
argv[9][strlen("--path=")] = '\0'; // NULL-terminate since strncpy doesn't
strncat(argv[9], path, strlen(path));
// Do stuff with array
printf("%s\n", argv[9]);
// Technically, you should never get here if execve succeeds since it will blow this
// entire program away (unless you are fork()'ing first)
free(argv[9]);
}
you can malloc the memory that strcat() will use, or you can use a larger-than-needed char buffer[N] on the stack.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char * someFunction();
int main(int argc, char ** argv) {
const char[] path = "commandName";
const char[] arg1 = "--config=moo";
const char[] arg2 = "--console";
const char[] arg3 = "--something=moo2";
//arg4 is skiiped
const char[] arg5 = "--format=x";
const char * mypath = someFunction();
const char[] pathprefix = "--path=";
size_t pathprefixlength = strlen(pathprefix);
size_t stringlength = pathprefixlength + strlen(mypath);
char * arg4 = (char *)malloc(stringlength + 1);
strcpy(arg4, pathprefix);
strcpy(arg4 + pathprefixlength, mypath);
arg4[stringlength] = '\0'; //null terminate
char *argvec[7]; // array of pointers
argvec[0] = path;
argvec[1] = arg1;
argvec[2] = arg2;
argvec[3] = arg3;
argvec[4] = arg4;
argvec[5] = arg;
argvec[6] = NULL;
//do something with argvec;
free(arg4);
}
Okay so basically I have a function that takes in a string and counts the lowercase tokens in it. I need to make a function that then returns an array of the lowercase tokens. I would need to use malloc to allocate enough memory for such array but I donโt know how to go about doing so.
Once the array is allocated how would I put the token strings into the array?
Any help is appreciated thank you