I am making a program that concatenates two strings given by user. Everything is fine, but I don't know why the program shows that the sizeof of the final result is 8-bit long. Doesn't matter how long the strings are, it always shows 8. I guess, that it is the size of char, but I would like to know why it acts this way. This is the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* concatenate(char *fir, char *sec)
{
int firLen = strlen(fir);
int secLen = strlen(sec);
int len = firLen + secLen + 1;
int i = 0,c=0;
int *wsk = &i;
char *result = (char *)malloc(len*sizeof(char));
while (fir[i]!='\0')
{
result[i]=fir[i];
(*wsk)++;
}
while (sec[c]!='\0')
{
result[i]=sec[c];
(*wsk)++;
c++;
}
result[len-1] = '\0';
return result;
}
int main(int argc, char **argv)
{
char *first, *second, *output;
int size1, size2;
printf("How long will your first string be: ");
scanf("%d", &size1);
first = (char *) malloc ((1+size1)*sizeof(char));
if (!first)
{
puts("\nError. Can't allocate memory!");
abort();
}
printf("How long will your second string be: ");
scanf("%d", &size2);
second = (char *) malloc ((size2+1)*sizeof(char));
if (!second)
{
puts("\nError. Can't allocate memory!");
abort();
}
printf("\nPlease, type in the first string: ");
scanf("%s",first);
printf("\nPlease, type in the second string: ");
scanf("%s",second);
output = (char *)malloc((size1+size2+1)*sizeof(char));
output = concatenate(first, second);
printf("\nConcatenation of the strings: %s", output);
printf("\n%d", sizeof(output));
free(first);
free(second);
free(output);
getchar();
return 0;
}
Don't use sizeof to determine string length, use the strlen function, as you're doing in other parts of your program.
printf("\nConcatenation of the strings: %s", output);
printf("\n%d", strlen(output));
Use sizeof to determine the size of data types, like char, a struct, an array, etc.
You've mentioned that you want to use sizeof to check if everything is fine with memory allocation, but you can't use sizeof this way on a buffer of memory allocated with malloc: you can only rely on the return value of malloc - which you aren't checking - to know if your allocation was successful.
You can use sizeof to determine the size of an array:
char myStr[13];
printf("%d\n", sizeof(myStr));
But this only works for arrays, and not buffers allocated using malloc.
Also this line creates a memory leak because you overwrite the pointer in the next line:
output = (char *)malloc((size1+size2+1)*sizeof(char));
sizeof gives the size in bytes, where a byte is the size of a char.
printf("\n%d", sizeof(output));
output is a char*, so on your system char*s are 8 bytes large. You must use strlen to obtain the length of a 0-terminated string.
printf("\n%d", sizeof(output)); prints a size of pointer to char. You platform appears to have pointers that are 8 bytes in size.
First:
second = (char *) malloc ((size2+1)*sizeof(char));
Don't typecast the result of malloc().
Second:
sizeof(char) is going to be 1, a char is 1 byte and sizeof() returns the number of bytes required to hold that data type. So you don't need the *sizeof(char), you need that for larger types like int.
Finally:
printf("\nConcatenation of the strings: %s", output); printf("\n%d", sizeof(output));
output is a char * so this is going to give you the sizeof(char *) on your system.
You said in a previous comment:
I know the differences between strlen and sizeof, but using sizeof(output) I wanted to check if everything is fine with memory allocation
Sounds like what you wanted was to verify that you allocated the correct amount of memory for the two concatenated strings. sizeof() won't give you that information. It's in the low level details at this point, you need to do something OS dependent to try and find that information. (ex. in the linux kernel if you kmalloc() memory you can use ksize() to find out exactly how many bytes you got)
Related
Hello I am working on a Caesar encryption program. Right now it takes as an input the file with the message to encrypt, the key
The input is currently in this format:
"text.txt", "ccc"
I need to convert this into taking a number so that it fits my requirements, so something like this:
"text.txt", "3"
Then i need to convert this "3" back into "ccc" so that the program still works. The logic being that 3 translates to the third letter of the alphabet "c", and is repeated 3 times. Another example would be if the key entered is "2", it should return "bb".
This is what i have so far but its giving me a lot of warnings and the function does not work correctly.
#include <stdio.h>
void number_to_alphabet_string(int n) {
char buffer[n];
char *str;
str = malloc(256);
char arr[8];
for(int i = 0; i < n; i++) {
buffer[i] = n + 64;
//check ASCII table the difference is fixed to 64
arr[i] = buffer[i];
strcat(str, arr);
}
printf(str);
}
int main(int argc, char *argv[]) {
const char *pt_path = argv[1]; //text.txt
char *key = argv[2]; //3
number_to_alphabet_string((int)key); //should change '3' to 'CCC'
}
Your problem is that you have a function
void number_to_alphabet_string(int n)
that takes an int but you call it with a char*
char* key = argv[2]; //3
number_to_alphabet_string(key);
My compiler says
1>C:\work\ConsoleApplication3\ConsoleApplication3.cpp(47,34): warning C4047: 'function': 'int' differs in levels of indirection from 'char *'
You need
char* key = argv[2]; //3
number_to_alphabet_string(atoi(key));
to convert that string to a number
With char *key = argv[2];, the cast (int) key does not reinterpret the contents of that string as a valid integer. What that cast does is take the pointer value of key, and interprets that as an integer. The result of this is implementation-defined, or undefined if the result cannot be represented in the integer type (a likely outcome if sizeof (int) < sizeof (char *)).
The C standard does not define any meaning for these values.
Here is a test program that, depending on your platform, should give you an idea of what is happening (or failing to happen)
#include <stdio.h>
int main(int argc, char **argv) {
if (sizeof (long long) >= sizeof (char *))
printf("Address %p as an integer: %lld (%llx)\n",
(void *) argv[0],
(long long) argv[0],
(long long) argv[0]);
}
As an example of implementation-defined behaviour, on my system this prints something like
Address 0x7ffee6ffdb70 as an integer: 140732773948272 (7ffee6ffdb70)
On my system, casting that same pointer value to (int) results in undefined behaviour.
Note that intptr_t and uintptr_t are the proper types for treating a pointer value as an integer, but these types are optional.
To actually convert a string to an integer, you can use functions such as atoi, strtol, or sscanf. Each of these have their pros and cons, and different ways of handling / reporting bad input.
Examples without error handling:
int three = atoi("3");
long four = strtol("4", NULL, 10);
long long five;
sscanf("5", "%lld", &five);
number_to_alphabet_string has a few problems.
malloc can fail, returning NULL. You should be prepared to handle this event.
In the event malloc succeeds, the contents of its memory are indeterminate. This means that you need to initialize (at least partially) the memory before passing it to a function like strcat, which expects a proper null terminated string. As is, strcat(str, arr); will result in undefined behaviour.
Additionally, memory allocated by malloc should be deallocated with free when you are done using it, otherwise you will create memory leaks.
char *foo = malloc(32);
if (foo) {
foo[0] = '\0';
strcat(foo, "bar");
puts(foo);
free(foo);
}
In general, strcat and the additional buffers are unnecessary. The use of char arr[8]; in particular is unsafe, as arr[i] = buffer[i]; can easily access the array out-of-bounds if n is large enough.
Additionally, in strcat(str, arr);, arr is also never null terminated (more UB).
Note also that printf(str); is generally unsafe. If str contains format specifiers, you will again invoke undefined behaviour when the matching arguments are not provided. Use printf("%s", str), or perhaps puts(str).
As far as I can tell, you simply want to translate your integer value n into the uppercase character it would be associated with if A=1, B=2, ... and repeat it n times.
To start, there is no need for buffers of any kind.
void number_to_alphabet_string(int n) {
if (1 > n || n > 26)
return;
for (int i = 0; i < n; i++)
putchar('A' + n - 1);
putchar('\n');
}
When passed 5, this will print EEEEE.
If you want to create a string, ensure there is an additional byte for the terminating character, and that it is set. calloc can be used to zero out the buffer during allocation, effectively null terminating it.
void number_to_alphabet_string(int n) {
if (1 > n || n > 26)
return;
char *str = calloc(n + 1, 1);
if (str) {
for (int i = 0; i < n; i++)
str[i] = 'A' + n - 1;
puts(str);
free(str);
}
}
Note that dynamic memory is not actually needed. char str[27] = { 0 }; would suffice as a buffer for the duration of the function.
A cursory main for either of these:
#include <stdio.h>
#include <stdlib.h>
void number_to_alphabet_string(int n);
int main(int argc, char *argv[]) {
if (argc > 1)
number_to_alphabet_string(atoi(argv[1]));
}
Note that with an invalid string, atoi simply returns 0, which is indistinguishable from a valid "0" - a sometimes unfavourable behaviour.
You can't use a cast to cast from a char array to an int, you have to use functions, such as atoi().
You never free your str after you allocate it. You should use free(str) when you no longer need it. Otherwise, it will cause a memory leak, which means the memory that you malloc() will always be occupied until your process dies. C doesn't have garbage collection, so you have to do it yourself.
Don't write things such as char buffer[n];, it can pass the compile of GCC, but it can't in MSVC.
And that isn't the stander way of declaring an array with variable length. use
char* buffer = malloc(n);
//don't forget to free() in order to avoid a memory leak
free(buffer);
I have a three row input file.
First row is an int, the second row is ints with space, the third row is a string.
I have to scan them than manipulate the string based on the ints.
My problem is that I can scan the ints, but scanning the string causes segmentation fault at fclose.
My code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE* in = fopen("be.txt", "r");
FILE* out = fopen("ki.txt", "w");
if(in==NULL){
printf("Error opening in!\n");
return -1;
}
if(out==NULL){
printf("Error opening out!\n");
return -1;
}
int brknglength, i;
fscanf(in, "%d", &brknglength);
printf("%d\n", brknglength);
int* seed[brknglength];
seed[brknglength] = malloc(sizeof(int[brknglength]));
for(i = 0; i < brknglength; i++){
if (fscanf(in, "%d", &seed[i]) != 1) {
printf("%d", i);
}
printf("%d.: %d \n", i, seed[i]);
}
char string;
fscanf(in, "%s", &string);
free(seed[brknglength]);
fclose(in);
fclose(out);
return 0;
}
What causes the segmentation fault?
Your first Problem appears here:
int* seed[brknglength];
This defines an array of int pointers on the stack.
seed[brknglength] = malloc(sizeof(int[brknglength]));
This initializes the element behind the array and overwrites your stack.
To fix it, use either:
int seed[brknglength]; /* use without free(seed) */
or:
int *seed = malloc(sizeof(int[brknglength]));
/* ... */
free(seed);
The latter also works for compilers, which do not support variable length arrays.
Your second problem is reading a string into a single char variable, which also overwrites the stack. Try something like:
char string[100];
fscanf(in, "%99s", &string);
Be aware, that "%s" stops at whitespace. Use something like "%99[^\t\n]" to define your own separators, or "%99c" for a fixed length string.
The GNU Compiler offers the modifier "m" (=allocate memory) as a convenient non-standard extension for all these cases:
char *string;
fscanf(in, "%ms", &string);
/* ... */
free(string);
int* seed[brknglength];
seed[brknglength] = malloc(sizeof(int[brknglength]));
It looks like what you tried to do here is make seed a pointer to an array of int and allocate space for it. However, that is the wrong syntax. Because [ ] has higher precedence than *, int* seed[brknglength]; defines an array of pointers to int. Also, the name of the object is seed, not seed[brknglength], so you would assign a value to it with seed = …, not with seed[brknglength] = ….
To make a pointer to an array and allocate space for it, use:
int (*seed)[brknglength];
seed = malloc(sizeof *seed);
Those can be combined (which is not a violation of the above note about using seed = for assignment—initialization has a special syntax):
int (*seed)[brknglength] = malloc(sizeof *seed);
However, you probably do not want that. If size is a pointer to an array, then you have to use *seed wherever you want to refer to the array. So fscanf(in, "%d", &seed[i]) would have to be fscanf(in, "%d", &(*seed)[i]).
Instead of making seed a pointer to an array, just make it a pointer to an int, and allocate space for as many int as you want:
int *seed = malloc(brknglength * sizeof *seed);
Then you can use seed[i] for element i of the array instead of having to use (*seed)[i].
char string;
That defines string to be a single char. But fscanf(in, "%s", &string); reads as many characters as the input has until a white-space character. So you need to pass fscanf a pointer to the first of many char. You can either declare string to be an array:
char string[100];
or a pointer to space that is allocated:
char *string = malloc(100 * sizeof *string);
Then you can use fscanf(in, "%s", string);. Note that you do not want to pass &string. That is the address of the array or of the pointer, depending on how you defined string. You want to pass the address of the first character, which is &string[0], or, equivalently, string. (If string is an array, it is automatically converted in this expression to a pointer to its first element, so it is equivalent to &string[0].)
Note that fscanf will read as many character as the input contains until a white-space character appears. That can exceed whatever size you provide for string. So you need to ensure the input does not have too many characters or tell fscanf to limit how much it reads, which you can do with:
fscanf(in, "%99s", string);
or:
int n = 99;
fscanf(in, "%*s", n, string);
Note that fscanf should be told to read at most one character less than the space in string because it needs to add a terminating null character.
To free these objects, use:
free(seed);
free(string); // (If defined as a pointer, not an array.)
I have an assignment I've been working on for a few hours now, and I can't seem to get it quite right. The assignment is to take a random number of names (from stdin), sort them, and then output them in alphabetical order. I can't find any sites online that handle this kind of sorting specifically, and have had no luck trying to implement qsort() into my code.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int stringcmp(const void *a, const void *b)
{
const char **ia = (const char **)a;
const char **ib = (const char **)b;
return strcmp(*ia, *ib);
}
void main(int argc, char *argv[])
{
char *input[] = {" "};
char temp[20][20];
int i = 0;
int num = 0;
int place = 0;
int stringlen = sizeof(temp) / sizeof(char);
printf("How many names would you like to enter? ");
scanf("%d", &num);
while (place < num)
{
printf("Please input a name(first only): ");
scanf("%s", input[place]);
printf("The name you entered is: ");
printf("%s\n", input[place]);
place++;
}
//qsort(temp, stringlen, sizeof(char *), stringcmp); <-- just an idea I was messing with
qsort(input, stringlen, sizeof(char *), stringcmp);
printf("Names:\n");
for(i=0; i<place; i++)
printf("%s\n", input[i]);
system("PAUSE");
return(EXIT_SUCCESS);
}
The main problem is, when I go to output my code, I cannot use the char *input variable because of how its declared. The temp[] will display, but will not be sorted by qsort because it is not declared as a pointer. Any ideas?
You can't declare your input array like that. Since you know how many the user requires, you can dynamically allocate the array:
char **input = malloc(num * sizeof(char*));
Likewise, when you read your strings in, they need somewhere to go. Simply passing an uninitialized pointer to scanf is not okay. I suggest you define the maximum length of a name and have a temporary buffer for reading it:
const size_t MAX_NAME = 50;
char name[MAX_NAME];
...
for( i = 0; i < num; i++ )
{
printf("Please input a name(first only): ");
scanf("%s", name);
input[i] = strdup(name);
}
[Note this does not prevent the user from overflowing the 'name' buffer. I used scanf for illustrative purposes only]
You seem to be passing the wrong array length to qsort. Try this:
qsort(input, num, sizeof(char *), stringcmp);
When you are finished, you need to release memory for all the names and the array.
for( i = 0; i < num; i++ ) free(input[i]);
free(input);
could you explain
the ** declarations throughout the code? I'm not sure what they're
used for, although I know the function for stringcmp is a widely used
algorithm, I have no idea how it works; I'm thrown off by the double
de-reference markers.
Yep, in the case where I used it, I am telling C that to get a single character, I have to dereference a pointer twice. When you index a pointer, it's dereferencing. So I allocated an array by requesting a block of memory containing num * sizeof(char*) bytes. Because I assigned that pointer to a char**, the compiler knows that I am pointing to a chunk of memory that contains char* values.
If I ask for input[0] (this is the same as *input) it should look at the very start of that memory and pull out enough bytes to form a char*. When I ask for input[1], it skips past those bytes and pulls out the next bunch of bytes that form a char*. Etc... Likewise, when I index a char*, I am pulling out single characters.
In your stringcmp function, you have the following situation. You passed a void* pointer to qsort so it doesn't actually know the size of the data values stored in your array. That's why you have to pass both the array length AND the size of a single element. So qsort just blindly rips through this arbitrary-length array of arbitrary-sized values and fires off memory addresses that ought to contain your data for comparison. Because qsort doesn't know anything else about your array elements except where they are located, it just uses void*.
But YOU know that those pointers are going to be the memory addresses of two of your array elements, and that your array elements are char*. So you need the address of a char* (hence you cast the pointers to char**). Now you need to dereference these pointers when you call strcmp() because that function requires a char* (ie a value that points directly to the memory containing your string characters). That is why you use the * in strcmp(*ia, *ib).
One quick way to fix your program is to declare input as an array of pointers, like this:
char *input[20];
When you read names in, use tmp[place] for your buffer, and store the pointer into input, like this:
scanf("%19s", tmp[place]);
input[place] = tmp[place];
Now sorting the input should work fine.
This has a limitation of being limited to 20 lines of 20 characters max. If you learned about malloc in the class, you should be able to fix that by allocating your strings and the string array dynamically.
I'm reading a C code that do
char * buf = malloc(sizeof (char *) * 16)
instead of
char buf[sizeof (char *) * 16]
what's the difference? well, I think the first expression unnecessary, if realloc() is not called, or am I wrong thinking?
char buf[sizeof(char*)*16] is an array allocated automatically, which is generally the stack. It is valid as long as buf is in scope, and there is sufficient stack space.
malloc allocates memory from some heap. It is valid until this memory is free()ed. Generally, there is much more heap available.
Yann's note is correct.
This appears to be an array of pointers. Since it is allocating memory for 16 times the size of a char pointer. Pointer size can vary on different systems. Pointers on some are 32-bit (4 bytes) where others are 64-bit (8 bytes).
char buf[sizeof(char *) * 16] is not an array of pointers, it's an array of chars that has elements equal to the size of a char pointer times 16.
Dynamic Array
The first one, is a dynamic array. The expression char * buf = malloc(sizeof (char *) * 16) stores the elements in memory ( the malloc is basically used for memory allocation ). The advantages of using it are, you can reallocate it, i.e resize it during runtime. However, you may have to allocate new memory every time you add a new element. Here's an example:
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
int main() {
int* array;
int n, i;
printf("Enter the number of elements: ");
scanf("%d", &n);
array = malloc(n*sizeof(int));
for (i=0; i<n; i++) {
printf("Enter number %d: ", i);
scanf("%d", &array[i]);
}
printf("\nThe Dynamic Array is: \n");
for (i=0; i<n; i++) {
printf("The value of %d is %d\n", i, array[i]);
}
printf("Size= %d\n", i);
getch();
return 0;
}
The output:
Automatic (Static?) Array
The second expression char buf[sizeof (char *) * 16] just declares a boring automatic array. It's size is static. No dynamic resizing, reallocation etc.
note: apologies for the type cast before malloc. typecasting the return value of malloc will result in the compiler not giving an error if you do something wrong. This may be followed by undefined runtime errors and debugging hell. Always avoid typecasting the result of malloc. Thanks #Lundin.
The main difference is that if this is code is in a function, you can still use the pointer declared in the former after you return.
I'm having a segmentation fault when I want to save a string in a dynamic array.
I have a program that does this:
User insert char "s"
The program enters a loop and save strings in an array (name: cod).
When user inserts char "t", it stops
After that I save that array in the first position of a new dynamic array (name: vec).
Then if user insert char "s" again
The program enters a loop and save strings in an array.
When user inserts char "t", it stops
After that I save that array in the second position of a new dynamic array.
and so one.
This is my code:
int main(){
char Cod[30][11];
char tmp[11];
char ***vec;
int i = 0;
strcpy (tmp, "p");
vec = (char *** ) malloc (sizeof ( char *) );
vec[0] = (char ** ) malloc (sizeof ( char *) * 30);
do {
scanf("%s", tmp);
while( (strcmp (tmp, "p")) != 0){
strcpy ( Cod[i] , tmp );
scanf("%s", tmp);
i++;
}
vec = (char ***) realloc (vec, sizeof ( char *) * (i + 1));
vec[i + 1] = (char ** ) realloc (vec[i + 1], sizeof ( char *) * (30));
vec[i-1] = (char **) Cod;
scanf("%s", tmp);
}
while((strcmp (tmp, "s")) == 0);
printf("%s", vec[0][0]);
return 0;
}
This is the part of the code that work's:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char Cod[30][11];
char tmp[11];
int i = 0;
strcpy (tmp, "p");
do {
scanf("%s", tmp);
while( (strcmp (tmp, "p")) != 0){
strcpy ( Cod[i] , tmp );
scanf("%s", tmp);
i++;
}
scanf("%s", tmp);
}
while((strcmp (tmp, "s")) == 0);
printf("%s", Cod[0]);
return 0;
}
I started to fix this code but soon realized there is so much wrong in it, I don't know where to start. So instead, this turned out to be a code review answer instead, I apologize up front if it is detailed and picky.
There's a rule of thumb in C saying that if you need more than two levels of pointer indirection, your code is obfuscated and should be rewritten (reference MISRA-C:2004 17.5).
It doesn't make sense whatsoever to use dynamic memory allocation in this case, because you already know at program start-up that no string will be larger than 11 characters and there will not be more than 30 strings. If this condition is not true, you need to write a safer input method, preferably with fgets() which is safe against buffer overflows. Make sure that the input doesn't go out of bounds of array "Cod". You can allocate 30*11=330 bytes statically without a guilty conscience. And it will make the code faster.
It doesn't make sense to have 3 levels of indirection for an array of strings. You aren't even using the dynamic memory to hold a copy of strings, you just allocate pointers. This doesn't make any sense at all. If you need a pointer lookup table pointing at Cod then allocate it statically, it will only require sizeof(char*)*30 bytes.
As already mentioned, you can only use realloc on a pointer that has previously been malloc/calloc:ed.
As already mentioned, never typecast the result of malloc/realloc in C. This is C++ practice. In C, it destroys type safety and hides type compatibility bugs. There are countless, detailed discussions about this here on SO if you want to know the details.
What if you don't find "p" in the user string? The program will go havoc.
Don't name variables that affect fundamental program functionality to abstract things like tmp, vec etc. tmp could be renamed to input_buf or something, etc.
Avoid magic numbers in code, use const or #define for array length constants.
You can initialize strings in C, there is no need for strcpy to do so. char input_buf[INP_BUF_N] = "p";
To search for a char in a string, use strchr().
You shouldn't need to have the user inputting the same thing twice with scanf() in the outer do-while loop, likely a typo bug.
You can not do wild typecast between a static array of arrays to a pointer-to-pointer. This depends on the structure of whatever the pointer-to-pointer points at. Because a typical dumb-school-book dynamic 2D-array (malloc(Xsizeof(char)... malloc(Y*sizeof(char)) will not allocate memory adjacently. Plenty of discussions about this here on SO.
(you can allocate dynamic 2D arrays in adjacent memory with the use of array pointers or with "mangling", but those are rather advanced topics)
free() the dynamic memory once you are done using it.
As you hopefully can tell, the wise choice here is to rewrite this code from scratch.
Since it is a homework I tried to rewrite your code in something that should work...
char Cod[30][11];
char tmp[11];
char ***vec;
int i = 0;
strcpy (tmp, "p");
vec = (char***)malloc(sizeof(char *));
vec[0] = (char**)malloc(sizeof(Cod));
do {
scanf("%s", tmp);
int j = 0;
while(strcmp(tmp, "p")) {
strcpy(Cod[j], tmp);
scanf("%s", tmp);
j++;
}
vec = (char ***)realloc(vec, sizeof(char *) * (i+1));
vec[i] = (char **)malloc(sizeof(Cod));
memcpy(vec[i], Cod, sizeof(Cod));//you need to copy results since next time the Cod will be rewritten
scanf("%s", tmp);
i++;
} while((strcmp(tmp, "s")) == 0);
for three stars
char ***vec;
you need 3 mallocs (the casts are, at best, redundant in C and may hide an error)
vec = malloc(sizeof *vec);
vec[0] = malloc(sizeof *vec[0]);
vec[0][0] = malloc(30 * sizeof *vec[0][0]); /* sizeof (char) is 1 by definition */
In this 2 lines:
vec = (char ***) realloc (vec, sizeof ( char *) * (i + 1));
vec[i + 1] = (char ** ) realloc (vec[i + 1], sizeof ( char *) * (30));
If i = 1, then you reserve to "vec" i+1=2 pointers. In the second line you then call the 3rd one (vec[i+1] = vec[2] is 3rd element in table of size 2).