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.
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;