Hey, having problems with what i thought was a simple piece of code, but when inputting anything more than 3 names, it ........s itself, both code and dumps are shown.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LENGTH 255
main()
{
//declare pointer and other vars
char **pt_bottom,**pt_counter,**pt_top;
int list_length;
char name[MAX_LENGTH];
//read in first int as length of the array
printf("Enter the number of names to be entered into the list:");
scanf("%d",&list_length);
//malloc pt_array to bottom and set the counter to bottom and top to the top of the list
pt_bottom=malloc(list_length*sizeof(char));
// printf("Allocating %d to pt_bottom\n",list_length*sizeof(char));
pt_counter=pt_bottom;
pt_top=pt_bottom+(list_length);
//for loop to get, trim, and malloc names
for(;pt_counter<pt_top;pt_counter++)
{
printf("Enter a name:");
scanf("%s",&name);
*pt_counter=malloc(sizeof(char)*(strlen(name)+1));
// printf("Allocating %d to pt_counter\n",sizeof(char)*(strlen(name)+1));
strcpy(*pt_counter,name);
}
//for loop to print names reversed
printf(":Results List:\n");
for(pt_counter--;pt_counter>=pt_bottom;pt_counter--)
{
printf("%s\n",*pt_counter); //on the last loop this is printing incorrectly (always "X?"
// printf("Printed\n");
free(*pt_counter); //this is where its failing on the last loop....
// printf("Freed\n");
}
//housekeeping
free(pt_bottom);
}//not working on anything more than 3 names, malloc error
Code:
*** glibc detected *** ./ex_13: double free or corruption (out): 0x0804a018 ***
======= Backtrace: =========
/lib/tls/i686/cmov/libc.so.6[0xb7e13d65]
/lib/tls/i686/cmov/libc.so.6(cfree+0x90)[0xb7e17800]
./ex_13[0x8048612]
/lib/tls/i686/cmov/libc.so.6(__libc_start_main+0xe0)[0xb7dc0050]
./ex_13[0x8048471]
======= Memory map: ========
08048000-08049000 r-xp 00000000 03:02 822669 /home/bolster/School/advanced_c/Coursework/ex_13
08049000-0804a000 rw-p 00000000 03:02 822669 /home/bolster/School/advanced_c/Coursework/ex_13
0804a000-0806b000 rw-p 0804a000 00:00 0 [heap]
b7c00000-b7c21000 rw-p b7c00000 00:00 0
b7c21000-b7d00000 ---p b7c21000 00:00 0
b7da9000-b7daa000 rw-p b7da9000 00:00 0
b7daa000-b7eee000 r-xp 00000000 03:02 574702 /lib/tls/i686/cmov/libc-2.6.1.so
b7eee000-b7eef000 r--p 00143000 03:02 574702 /lib/tls/i686/cmov/libc-2.6.1.so
b7eef000-b7ef1000 rw-p 00144000 03:02 574702 /lib/tls/i686/cmov/libc-2.6.1.so
b7ef1000-b7ef4000 rw-p b7ef1000 00:00 0
b7efb000-b7f05000 r-xp 00000000 03:02 540678 /lib/libgcc_s.so.1
b7f05000-b7f06000 rw-p 0000a000 03:02 540678 /lib/libgcc_s.so.1
b7f06000-b7f0a000 rw-p b7f06000 00:00 0
b7f0a000-b7f24000 r-xp 00000000 03:02 541509 /lib/ld-2.6.1.so
b7f24000-b7f26000 rw-p 00019000 03:02 541509 /lib/ld-2.6.1.so
bf85b000-bf870000 rw-p bf85b000 00:00 0 [stack]
ffffe000-fffff000 r-xp 00000000 00:00 0 [vdso]
Aborted (core dumped)
Running on ubuntu 7.10
A fresh pair of eyes would be greatly appreciated.