Reputation: 115
I am trying to write a function to assign text input to a char**
. Where each word is stored in a char*
. When I was doing this I was getting errors that I think indicated that I didn't allocate enough memory so I wrote a little test program.
#include <stdio.h>
#include <stdlib.h>
int main(){
char **input=NULL;
char **help=NULL;
for(int i=1;i<300;i++){
help=realloc(input,i*(sizeof(char*)));
if (!help)
return 0;
input=help;
input[i]="test";
}
return 1;
}
Now this works just fine, but when I assign per character as follows.
#include <stdio.h>
#include <stdlib.h>
int main(){
char **input=NULL;
char **help=NULL;
char *help2=NULL;
for(int i=1;i<300;i++){
help=realloc(input,i*(sizeof(char*)));
if (!help)
return 0;
input=help;
for (int j=1;j<5;j++){
help2=realloc(input[i-1],j);
if (!help2)
return 0;
input[i-1]=help2;
input[i-1][j-1]='t';
}
}
return 1;
}
I get a segmentation fault on line 14. I think this is because the input
does not have enough space. But since the size of a character is one and I used sizeof(char*)
I don't see how it is not enough. How much memory would I need to allocate and why did it work in my first example? Thanks!
Upvotes: 2
Views: 96
Reputation: 164639
clang
finds the problem right away.
test(72707,0x7fffe32443c0) malloc: *** error for object 0x7fffe0051090: pointer being realloc'd was not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap: 6
The problem is here.
help2=realloc(input[i-1],j);
While input
has been allocated, none of its elements have been initialized. realloc
will act like malloc
if the pointer is null, but if its asked to reallocate the uninitialized garbage pointer in input[i-1]
it will freak.
Instead you must properly initialize input
before trying to realloc
its elements.
A memory checking tool such as Valgrind will help find these sorts of mistakes.
Upvotes: 1