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 Overflow
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 616347 โ€บ java โ€บ char-array-initialization-dynamically
char array initialization dynamically (Beginning Java forum at Coderanch)
And also ... taking guesses on what is implied from the pseudo code ... it looks like you are trying to store each car's name, which is a string, into a single character. This doesn't sound reasonable, does it? Henry ยท Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor) ... k... sorry.. got my mistakes.. thanks a lot!! so i think i have to initialize my array directly like char strtsnh[] = {'hyundai','bmw'};
Top answer
1 of 2
5

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  ));
  }
}
2 of 2
2

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
} 
Discussions

How can I create a character array in Java without a specified length? - Stack Overflow
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 chars = new ArrayList<>(); // ... Java Tutorials > Trail: Collections > The List Interface More on stackoverflow.com
๐ŸŒ stackoverflow.com
Converting String[] array to dynamic char[] array in java? - Stack Overflow
Yes ofcourse,,I know and that words ... should be my output..!! dynmic names in the char array..?? 2014-02-22T06:11:57.927Z+00:00 ... You mean, you want your standard output to be formatted like Java code? Why? Java is not a dynamic language, so you can't create arbitrary dynamic ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
May 22, 2017
C Dynamic char array - Stack Overflow
Expanding array dynamicly after user enter string in function dynamic_array My Problem seems to be when i try to use the extended array agian in main after i dynamic_array returns true. After func... More on stackoverflow.com
๐ŸŒ stackoverflow.com
May 23, 2017
c - Creating a dynamic char array - Stack Overflow
I am trying to read in the a file and store the words into a dynamic char array. Right now I am getting a Segmentation fault (core dumped) error. I have tried using strdup() and strcpy() still i am More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Quora
quora.com โ€บ How-do-I-dynamically-allocate-a-char-array-using-a-malloc-function-in-C
How to dynamically allocate a char array using a malloc function in C - Quora
In order to allocate memory dynamically using C language the following code will be enough: char *s = (char *)malloc(20 * sizeof(char)); The above line allocates memory for storing 20 characters or in fact 19 ch...
๐ŸŒ
Javatpoint
javatpoint.com โ€บ character-array-in-java
Character Array in Java - Javatpoint
Character Array in Java - Character Array in Java with java tutorial, features, history, variables, object, programs, operators, oops concept, array, string, map, math, methods, examples etc.
Find elsewhere
๐ŸŒ
Cprogramming
cboard.cprogramming.com โ€บ c-programming โ€บ 143349-dynamic-char-array-allocation-assignment.html
Dynamic char array allocation and assignment
November 16, 2011 - The only tricky part is you need (*game)[i] since *game[i] means something different (specifically, take game[i] as a pointer and dereference it, which is different from what you want - take game as a pointer, dereference it to get an array, and then get entry i from that array). No real reason to pick this versus the "return a pointer" approach until you have a function which allocates more than one pointer. Since you can only return one value, you'd need a different approach in that case. ... void allocate_memory(char ***game) { *game = malloc(8 * sizeof(char*)); int i; for(i = 0; i < 8; i++) (*game)[i] = malloc(8 * sizeof(char)); } int main () { char **game; char pawns[8] = "rbnqknbr"; allocate_memory(&game); for(int j=0; j<8; j++) game[0][j] = pawns[j]; }
๐ŸŒ
Edureka
edureka.co โ€บ blog โ€บ character-array-in-java
Char Array In Java | Introduction To Character Arrays In Java | Edureka
July 5, 2024 - Java which is one of the best programming languages makes use of char array to hold data. In this article we would exploring everything that is there to know about them. ... Char Arrays are highly advantageous. It is a noted fact that Strings are immutable i.e. their internal state cannot be changed after creation.
๐ŸŒ
Huda Tutorials
hudatutorials.com โ€บ java โ€บ basics โ€บ java-arrays โ€บ java-char-array
Java char Array - char array in java - Huda Tutorials
July 16, 2021 - If you try to store long (big) elements in array, you will get performance problems. If you overcome performance problems you should go to java collections framework or simply use Vector. ... /* Java char Array Example Save with file name CharArray.java */ public class CharArray { public static void main(String args[]) { // JAVA CHAR ARRAY DECLARATION char c[]; // MEMORY ALLOCATION FOR JAVA CHAR ARRAY c = new char[4]; // ASSIGNING ELEMENTS TO JAVA CHAR ARRAY c[0] = 'a'; c[1] = 'c'; c[2] = 'D'; c[3] = 'B'; // JAVA CHAR ARRAY OUTPUT System.out.println("Java char Array Example"); for(int i=0;i<c.length;i++) { System.out.println("Element at Index : "+ i + " " + c[i]); } } }
๐ŸŒ
Dot Net Perls
dotnetperls.com โ€บ char-array-java
Java - char Array - Dot Net Perls
January 25, 2024 - To begin, char arrays support the array initializer syntax like other arrays. Here we create a new array with 3 elements. Tip Int values, which represent chars in ASCII, can also be used in a char array initializer.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ c language โ€บ how-to-create-a-dynamic-array-of-strings-in-c
How to Create a Dynamic Array of Strings in C? - GeeksforGeeks
July 23, 2025 - To create a dynamic array of strings in C, we can use the concept of double pointer and dynamic memory allocation. The double pointer is the pointer that stores the memory address of another pointer.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ creating-a-dynamic-array-in-java
Dynamic Array in Java - GeeksforGeeks
November 13, 2024 - Also, update the values of new array with the double default size. ... Implementation: This concept can be implemented using new user defined class so to use the methods and properties together. ... // Java Program to Implement a Dynamic Array // User Defined Array class Array { private int arr[]; private int count; // Method to return length of array public Array(int size){ arr = new int[size]; } // Method to print array public void printArray(){ for (int i = 0; i < count; i++) System.out.print(arr[i] + " "); } // Method to insert element in array public void insert(int ele){ if (arr.length =
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 55875518 โ€บ creating-a-dynamic-char-array
c - Creating a dynamic char array - Stack Overflow
char ** array; int main(int argc, char * argv[]){ int size = 0; int i; FILE * file; char * line; size_t len; ssize_t read; file = fopen("wordsEn.txt", "r"); if(file == NULL){ printf("Error coudl not open wordsEn.txt\n"); return -1; } while((read = getline(&line, &len, file)) != -1){ size++; } array = (char **) malloc((sizeof(char *) * size)); rewind(file); i = 0; while((read = getline(&line, &len, file)) != -1){ //strcpy(array[i], line); array[i] = strdup(line); i++; } for(i = 0; i < size; i++){ printf("%s", array[i]); } } I am expecting for example array[0] to return the string 'alphabet' ... store the words into a dynamic char array โ€“ What does that mean?
Top answer
1 of 4
1

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]);
}
2 of 4
1

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);
}
๐ŸŒ
Upgrad
upgrad.com โ€บ home โ€บ blog โ€บ software development โ€บ complete guide to char in java: declaration, size, common use cases and more
Exploring Char in Java: Size, Declaration, and Applications
June 11, 2025 - Step 2: Initialize the Char Array After declaration, you can initialize the array with predefined values or by dynamically assigning values using loops.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnprogramming โ€บ how to dynamically allocate an array and add strings to it? (in c)
r/learnprogramming on Reddit: How to dynamically allocate an array and add strings to it? (In C)
February 17, 2022 -

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

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ c language โ€บ dynamic-array-in-c
Dynamic Array in C - GeeksforGeeks
July 23, 2025 - Array in C is static in nature, so its size should be known at compile time and we can't change the size of the array after its declaration. Due to this, we may encounter situations where our array doesn't have enough space left for required elements or we allotted more than the required memory leading to memory wastage. To solve this problem, dynamic arrays come into the picture.