The problem is in how you're using malloc
. You're not allocating enough memory, and you can't know how much memory to allocate.
strings=malloc(r*sizeof(strings));
This allocates enough memory in strings
for r
character pointers. strings
can now safely store r
variables of type char *
. Trouble is you never allocate memory for the strings stored in strings
.
void func(char *p[],int r)
{
int i;
for(i=0;i<r;i++)
/* At this point, p[i] is unallocated */
scanf("%s",p[i]);
}
p[i]
, the thing actually storing the string, also has to be allocated. How much? Who knows, you're reading from input using scanf
. So first cut is to allocate a fixed size and only read at most that size (less one because of the null character).
void func(char *p[],int r)
{
int i;
for( i=0; i < r; i++ ) {
p[i] = malloc( 256 * sizeof(char) );
scanf("%255s",p[i]);
}
}
Never use scanf %s
without a max length else the input can be larger than the memory you allocated. Also don't use scanf
, it can get you into trouble if the input doesn't match your pattern. It's better to read the whole line with getline
or fgets
and then sscanf
if necessary.
A memory checker is absolutely essential when coding in C. It will find these problems for you. I use valgrind.
Enter the no. of rows :5
foo
==10082== Use of uninitialised value of size 8
==10082== at 0x1001F2121: __svfscanf_l (in /usr/lib/system/libsystem_c.dylib)
==10082== by 0x1001EA979: scanf (in /usr/lib/system/libsystem_c.dylib)
==10082== by 0x100000F2B: func (test.c:19)
==10082== by 0x100000EBD: main (test.c:11)
==10082==
==10082== Invalid write of size 1
==10082== at 0x1001F2121: __svfscanf_l (in /usr/lib/system/libsystem_c.dylib)
==10082== by 0x1001EA979: scanf (in /usr/lib/system/libsystem_c.dylib)
==10082== by 0x100000F2B: func (test.c:19)
==10082== by 0x100000EBD: main (test.c:11)
==10082== Address 0x0 is not stack'd, malloc'd or (recently) free'd
Those are stack traces pointing at memory problems. "Use of uninitialised value of size 8" tells me I failed to allocate memory for a string. The stack tells me it's the scanf
in func
.