简体   繁体   中英

dynamical memory allocation and return value 3221225477

I am doing my homework, the problem is as follows:

  1. accept words separated by commas.
  2. extracted each word and reverse them.
  3. put them back in order.

for example, if I enter "apple,egg", I get "elppa,gge"

So far I've completed most of the program, the program works well when I enter less than four words, but with more than four words such as "ybur,etaga,etiluzal,iluzal sipal,etihcalam" the program doesn't work and it shows me return value 3221225477. I just learned how to use dynamical memory allocation so I think it may result from the fact that I did not use it properly, if that's true, please correct me.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[]) {
    int c=1,i,s;
    char a[1000];
    fgets(a,1000,stdin);
    for(i=0;i<strlen(a);i++){
        if(a[i]=='\n'){
            a[i]='\0';
        }
    } 
    for(i=0;i<strlen(a);i++){
        if(a[i]==','){
            c++;
        }
    }
    char **b;
    b=(char**)malloc(sizeof(char)*c); 
    for(i=0;i<c;i++){
        b[i]=(char*)malloc(sizeof(char)*100);
    }
    strcpy(b[0],strtok(a,","));
    for(i=1;i<c;i++){
        strcpy(b[i],strtok(NULL,","));
    }
    char **d;
    d=(char**)malloc(sizeof(char*)*c);
    for(i=0;i<c;i++){
        d[i]=(char*)malloc(sizeof(char)*strlen(b[i]));
        for(s=0;s<strlen(b[i]);s++){
            d[i][s]=b[i][strlen(b[i])-s-1];
        }
    }
    printf("%s",d[0]);
    for(i=1;i<c;i++){
        printf(",%s",d[i]);
    }
    for(i=0;i<c;i++){
        free(b[i]);
        free(d[i]);
    }
    free(b);
    free(d);
    return 0;
}

I hope that the program works no matter what words I enter.

b=(char**)malloc(sizeof(char)*c); 

should be

b = malloc(sizeof(char *) * c); 
                       ^--------------(sizeof pointer)

As of now you are only allocating sizeof char * c to char ** as it should be sizeof pointer * c .

Also you don't need to cast the malloc return.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM