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
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
} 
๐ŸŒ
Reddit
reddit.com โ€บ r/cpp_questions โ€บ how do i cin and cout dynamic char arrays in c++? (example names)
r/cpp_questions on Reddit: How do I cin and cout dynamic char arrays in c++? (example names)
August 8, 2021 -

hey! I am stuck on this question, I have to cin and cout a dynamic array of characters (not using library function/ c++ string types), here are the two issues i am facing:

  1. I do not know how long the name would be so should I just take a precondition that it should be smaller than let's say 100? or is there a way that I can create a dynamic array without specifying coloum size?

  2. this code that i came up with is producing weird result and i have no clue how to correct it T_T

I would be really thankful if you all can help me with this T_T.

my needed output should look something like:

enter name #1: abc def

enter name #2: ghi jkl...

.

.

.

enter name #n: nnn mmm

int main() 
{
	int n, j=0;
	cout<<"How many names do you want to enter ? ";
	cin>>n;
	char** name = new char*[n];
	for(int i=0; i<n; i++)
	{
		name[i]=new char[100];
	}
	for(int i=0; i<n; i++)
	{
		cout<<"enter name #"<<i+1 <<" :";
		do
		{
			cin>>name[i][j];
			j++;
			
		}while(name[i][j]!='\n');
	}
	for(int i=0; i<n; i++)
	{
	    for(int j=0; name[i][j]!='\n' ; j++)
	    {
	        cout<<name[i][j];
	    }
	    cout<<endl;
	}
}

Edit: Thank You so much for helping me with this problem however I figured a way to do it, it's definitely not the best or the most useful but our professor won't vibe with any other straight ways lmao here's what I came up with and the output I get, please let me know what yall think!

int main() 
{
	int n;
	
	cout<<"How many names do you want to enter ? ";
	cin>>n;
	char** lastname = new char*[n];
	for(int i=0; i<n; i++)
		lastname[i]=new char[100];
		
	char ** firstname = new char*[n];
	for(int i=0; i<n; i++)
	    firstname[i]=new char[100];
		
	for(int i=0; i<n; i++)
	{
		cout<<"enter name #"<<i+1 <<" :";
	   	   cin>>firstname[i]>>lastname[i];
	   	   
	}
	
	for(int i=0; i<n; i++)
	{
	    cout<<firstname[i]<<" "<<lastname[i];
	    cout<<endl;
	}
	
}

/* OUTPUT :
How many names do you want to enter ? 3
enter name #1 :Fucker Certified
enter name #2 :Flex Offender
enter name #3 :Billy Balls
Fucker Certified
Flex Offender
Billy Balls
*/

I am pretty sure it's not the most efficient but this was all I could think of T_T

once again Thank You so muchhh!!

Top answer
1 of 2
10
That is the C way and therefore is an absolutely awful C++ question. Anyway you need to use this function: https://en.cppreference.com/w/cpp/io/basic_istream/getline Every time the function fails because the buffer is too small you will have to release the buffer and reserve a larger buffer.
2 of 2
4
Yikes! You can't use either getline or standard string? Your teacher is shit. I don't care what they think they're doing, teaching you low level semantics - this isn't the way to do it. By the time you're here, writing user IO, such lessons should be behind you. Arbitrary limits are the mark of a bad teacher and a bad lesson plan. With that aside, you need to implement your own string and your own getline, and apparently your own vector. I hope you already know how to write functions, and can use those. If you're not allowed to use a function, consider dropping out or petitioning to switch to a teacher who has a fucking clue how to do their job. To implement a dynamic container, you need 3 pointers: using pointer = T*; using reference = T&; pointer first, last, total; Then to allocate: void alloc(size_t size) { first = new T[size]; last = first; total = first + size; } Reallocation is always a doubling: size_t cap() { return total - first; } size_t size() { return last - first; } void copy_to(pointer dest) { for(auto iter = first; iter != last; ++iter) { dest[iter - first] = *iter; } } void realloc() { auto tmp_cap = cap(); auto tmp_size = size(); pointer tmp = new T[tmp_cap * 2]; copy_to(tmp); delete first; first = tmp; last = first + tmp_size; total = first + tmp_cap; } Wrap this stuff up in a class. This is basically how vectors and strings work. If you can make it a template, then you can use your new container type for both. You'll have to flesh out the rest of the code, including adding a new element to the buffer, probably with a push_back method. You'll have to see if you have capacity to add one more, and if not, reallocate. Otherwise, you add your new element to last, then ++last. Then you need to replicate getline. This is simply extracting one character at a time and checking if it's equal to a delimiter. If it isn't the delimiter, you push back onto your string. If it is the delimiter, you disregard it and stop your extracting loop. I'll leave this one entirely up to you. Finally, you need to be able to print your string type: ostream &operator <<(ostream &os, const your_string_type &str) { for(size_t i = 0; i < str.size(); ++i) { os << str[i]; } return os; } This is "operator overloading" syntax. You can write custom operators for almost anything. I made the presumption you would have written a reference operator[](size_t offset) hint hint for your string type. I'm omitting a lot because I'm not going to do your homework for you, but I hope I've given you some insight. If you can't use any of this for your homework, then I hope I've kind of blown your mind.
๐ŸŒ
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...
๐ŸŒ
Cplusplus
cplusplus.com โ€บ forum โ€บ beginner โ€บ 169561
Dynamic character array - C++ Forum
July 14, 2015 - If you know the string won't be longer than some value, you can create a char buffer that large. Or if you really want to dynamically allocate that string: ... Topic archived. No new replies allowed. Home page | Privacy policy ยฉ cplusplus.com, 2000-2025 - All rights reserved - v3.3.3 Spotted an error?
๐ŸŒ
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]; }
๐ŸŒ
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.
๐ŸŒ
Arduino Forum
forum.arduino.cc โ€บ projects โ€บ programming
dynamic allocation for char* - Programming - Arduino Forum
February 3, 2021 - Hi, I'm trying to allocate a char* dynamically to avoid fixed size char arrays. I saw that Strings aren't recommended so I tried to use char* instead but it's not that easy. I'm working with an ESP8266 My goal is to copy 3 char arrays into one. Here is my code: char * cr; void setup() { char ca[] = "test"; char cb[] = "test2"; char cc[] = "test3"; int lena, lenb, lenc, total; Serial.begin(115200); while (!Serial) { } delay(200); Serial.println("Starting"); // put your ...
Find elsewhere
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ c language โ€บ dynamic-array-in-c
Dynamic Array in C - GeeksforGeeks
July 23, 2025 - The elements of the array are: ... method in C is used to dynamically allocate the specified number of blocks of memory of the specified type and initialized each block with a default value of 0....
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 55875518 โ€บ creating-a-dynamic-char-array
c - Creating a dynamic char array - Stack Overflow
Note you do not have to read two times the file, you can use malloc then realloc to increase the size of the (really) dynamic array ... #include <stdlib.h> #include <stdio.h> #include <string.h> int main() { char ** array = malloc(0); size_t size = 0; 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 (line = NULL, len = 0, (read = getline(&line, &len, file)) != -1){ array = realloc(array, (size+1) * sizeof(char *)); array[size++] = line; } free(line); /* do not forget to free it */ fclose(file); for(size_t i = 0; i < size; i++){ printf("%s", array[i]); } /* free resources */ for(size_t i = 0; i < size; i++){ free(array[i]); } free(array); return 0; }
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 40411419 โ€บ c-char-array-c-string-dynamic
C char array (C string) dynamic? - Stack Overflow
UB can include seeming to work under 100% of test cases then crashing at midnight on your customers production system. Or allowing hackers to download all user info in your account database. Or turning on the lights of the White House xmas tree ... The behavior is undefined because you haven't allocated memory for the array items. Try this: char sss[3]; Now you can assign to the individual array indexes without undefined behavior.
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);
}
๐ŸŒ
Cplusplus
cplusplus.com โ€บ forum โ€บ beginner โ€บ 72126
Dynamic char array length - C++ Forum
C Strings are null terminated. You're not allocating enough space for the text and the null. And you're not placing the null at the end of the string. You need these changes: char* fWord = new char[fWordLen + 1]; ... fWord[fWordLen] = '\0'; You also need to return something if you have leading spaces, null probably. ... Oh right, I was using '/n' instead of '/0'. Thanks, that fixed it. ... Using arrays of char to represent strings.
๐ŸŒ
Cplusplus
cplusplus.com โ€บ forum โ€บ beginner โ€บ 284776
Program with dynamic char array just ski - C++ Forum
September 4, 2022 - The code doesn't use a dynamic array. I'll give you a hint, when passing a regular char array/C string into a function you can't use strlen to find out it's length. That information is lost when the array devolves to a pointer.
๐ŸŒ
Ohio-state
web.cse.ohio-state.edu โ€บ ~reeves.92 โ€บ CSE2421au12 โ€บ SlidesDay11.pdf
Character Array (i.e. string) example
Managing Director, Imageomics Institute and AI and Biodiversity Change Glob, Computer Science and Engineering