J
John Green
Hi,
I was learning how to use valgrind and was trying various projects and
checking the results. I used the following source code and I was
surprised by results. When I run the program with 1 argument I get a
memory leak. If I run the program with 2 or more arguments I valgrind
reports no memory leak.
So is there a memory leak??
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv) {
size_t numofelements;
size_t temp;
char **stringarray;
numofelements=argc-1;
if (numofelements == 1) {
numofelements=strlen(argv[1]);
stringarray=malloc(numofelements * sizeof(*stringarray));
if (stringarray == NULL) {
printf("can't allocate memory\n");
exit(EXIT_FAILURE);
}
for (temp=0; temp < numofelements; temp++) {
stringarray[temp]= malloc(2 * sizeof(char)); /* space for letter
+ \0 char */
if (stringarray[temp] == NULL) {
printf("can't allocate memory\n");
exit(EXIT_FAILURE);
}
strncpy(&stringarray[temp][0], &argv[1][temp], 1);
strncpy(&stringarray[temp][1], "\0", 1);
}
}
else {
stringarray=malloc(numofelements * sizeof(*stringarray));
if (stringarray == NULL) {
printf("can't allocate memory\n");
exit(EXIT_FAILURE);
}
for (temp=0; temp < numofelements; temp++) {
stringarray[temp] = argv[temp+1];
}
}
for (temp=0; temp < numofelements; temp++) {
printf("%s\n", stringarray[temp]);
}
free(stringarray);
return 0;
}
I was learning how to use valgrind and was trying various projects and
checking the results. I used the following source code and I was
surprised by results. When I run the program with 1 argument I get a
memory leak. If I run the program with 2 or more arguments I valgrind
reports no memory leak.
So is there a memory leak??
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv) {
size_t numofelements;
size_t temp;
char **stringarray;
numofelements=argc-1;
if (numofelements == 1) {
numofelements=strlen(argv[1]);
stringarray=malloc(numofelements * sizeof(*stringarray));
if (stringarray == NULL) {
printf("can't allocate memory\n");
exit(EXIT_FAILURE);
}
for (temp=0; temp < numofelements; temp++) {
stringarray[temp]= malloc(2 * sizeof(char)); /* space for letter
+ \0 char */
if (stringarray[temp] == NULL) {
printf("can't allocate memory\n");
exit(EXIT_FAILURE);
}
strncpy(&stringarray[temp][0], &argv[1][temp], 1);
strncpy(&stringarray[temp][1], "\0", 1);
}
}
else {
stringarray=malloc(numofelements * sizeof(*stringarray));
if (stringarray == NULL) {
printf("can't allocate memory\n");
exit(EXIT_FAILURE);
}
for (temp=0; temp < numofelements; temp++) {
stringarray[temp] = argv[temp+1];
}
}
for (temp=0; temp < numofelements; temp++) {
printf("%s\n", stringarray[temp]);
}
free(stringarray);
return 0;
}