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
}
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:
-
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?
-
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!!
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?
In C a string is a char*. A dynamic array of type T is represented as a pointer to T, so for char* that would be char**, not simply a char* the way you declared it.
The compiler, no doubt, has issued some warnings about it. Pay attention to these warnings, very often they help you understand what to do.
Here is how you can start your testing:
char **aPtr;
int len = 1; // Start with 1 string
aPtr = malloc(sizeof(char*) * len); // Do not cast malloc in C
aPtr[0] = "This is a test";
printf("%s",aPtr[0]); // This should work now.
char *str; //single pointer
With this you can store one string.
To store array of strings you Need two dimensional character array
or else array of character pointers or else double pointer
char str[10][50]; //two dimensional character array
If you declare like this you need not allocate memory as this is static declaration
char *str[10]; //array of pointers
Here you need to allocate memory for each pointer
loop through array to allocate memory for each pointer
for(i=0;i<10;i++)
str[i]=malloc(SIZE);
char **str; //double pointer
Here you need to allocate memory for Number of pointers and then allocate memory for each pointer .
str=malloc( sizeof(char *)*10);
And then loop through array allocate memory for each pointer
for(i=0;i<10;i++)
str[i]=malloc(SIZE);
The problem is you are dereferencing an uninitialized variable. You need to allocate memory for str somehow.
Fortunately for you, there is a function that does this for you, called getline().
char * get_info(char *ch) {
char *str;
printf("Enter a sentence to seach: ");
str = NULL;
getline(&str, NULL, stdin);
printf("Enter a character to search for: ");
*ch = getchar();
return str;
}
the declaration char* str, can be read as str is a variable that will hold a pointer to a character. No where in your code do you actually allocate this memory for a character (or an array of characters)
If you were to do the following:
char *str;
str = malloc(15*sizeof(char));
You have not only declared that str will contain a pointer to a character (or an array of characters), but also allocated this memory.
Now while this solves your original question, as jxh points out, this introduces another error. This code suffers from a classical heap-based buffer overflow, in that if I supply an input line with, say, 30 characters I will use all the memory allocated to the array and over-write other data.
Additionally, you do need to guard against memory allocation failure and attempt to gracefully handle it.
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);
}
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;